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

1

5

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.

Leelah answered 26/4, 2021 at 7:56 Comment(0)
T
10

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(
          //..
       )
}
Tolbert answered 26/4, 2021 at 8:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.