2

How do I use selectableButtonBackground attribute on a custom View that uses Anko's apply() method inside its constructor like the following structure?

class XPTO(context: Context) : CardView(context) {

    init {
         this.apply {
             // I'd like to invoke selectableButtonBackground here
         }
}

I've tried to do context.obtainStyledAttributes(arrayOf(R.attr.selectableItemBackground).toIntArray()).getDrawable(0) but with no success.

2 Answers 2

2

I just created an extension function to get the resource ids for attributes.

val Context.selectableItemBackgroundResource: Int get() {
    return getResourceIdAttribute(R.attr.selectableItemBackground)
}

fun Context.getResourceIdAttribute(@AttrRes attribute: Int) : Int {
    val typedValue = TypedValue()
    theme.resolveAttribute(attribute, typedValue, true)
    return typedValue.resourceId
}

This way you can also add more attributes if needed. Example to put it in anko:

frameLayout {
   textView {
      text = "Test"
      backgroundResource = selectableItemBackgroundResource
      isClickable = true
   }
}

Don't forget the isClickable, else you won't see anything when you're clicking the textView

0

Another way to achieve this with Anko:

val backgroundResource = attr(R.attr.selectableItemBackgroundBorderless).resourceId

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.