Search code examples
androidkotlinandroidxmaterial-components-androidandroid-annotations

Kotlin issue when trying to cast "attachBadgeDrawable": This declaration is opt-in


I would use the BadgeDrawable in my Android app on a Button, the issue is that when i'm trying to set to the button layout the badgeDrawable via attachBadgeDrawable i get an error on it which says:

his declaration is opt-in and its usage should be marked with  '@com.google.android.material.badge.ExperimentalBadgeUtils' or '@OptIn(markerClass = com.google.android.material.badge.ExperimentalBadgeUtils.class)'

The code where i use that piece of code is the following:

            btnInvia.viewTreeObserver.addOnGlobalLayoutListener(
                object : OnGlobalLayoutListener {
                    override fun onGlobalLayout() {
                        val badgeDrawable = BadgeDrawable.create(requireContext())
                        badgeDrawable.number = corpo
                        badgeDrawable.verticalOffset = 20
                        badgeDrawable.horizontalOffset = 15
                        BadgeUtils.attachBadgeDrawable(badgeDrawable, btnInvia, layoutInvia)
                        btnInvia.viewTreeObserver.removeOnGlobalLayoutListener(this)
                    }

                }
            )

if it could be usefull the min SDK is 24.


Solution

  • The class BadgeUtils is marked with the androidx annotation @Experimental. In this way it is reported the usages of experimental API in this case with a level = ERROR.

    In your method you have to use one of these annotations to suppress the report:

    @ExperimentalBadgeUtils
    @UseExperimental(markerClass = ExperimentalBadgeUtils::class)
    fun onCreate(savedInstanceState: Bundle?) {
        //...
       btnInvia.viewTreeObserver.addOnGlobalLayoutListener(
          //..
       )
    }
    

    You can also use the kotlin annotation @OptIn:

    @OptIn(ExperimentalBadgeUtils::class)
    fun onCreate(savedInstanceState: Bundle?) {
            //...
           btnInvia.viewTreeObserver.addOnGlobalLayoutListener(
              //..
           )
    }