Android 如何在Anko上使用selectableButtonBackground?

Android 如何在Anko上使用selectableButtonBackground?,android,kotlin,anko,Android,Kotlin,Anko,如何在自定义视图上使用selectableButtonBackground属性,该视图在其构造函数中使用Anko的apply()方法,如以下结构所示 class XPTO(context: Context) : CardView(context) { init { this.apply { // I'd like to invoke selectableButtonBackground here } } 我尝试过使用con

如何在自定义视图上使用
selectableButtonBackground
属性,该视图在其构造函数中使用Anko的
apply()
方法,如以下结构所示

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

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

我尝试过使用context.obtainStyledAttributes(arrayOf(R.attr.selectableItemBackground).ToInArray()).getDrawable(0),但没有成功。

我只是创建了一个扩展函数来获取属性的资源ID

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
}
这样,如果需要,还可以添加更多属性。将其放在anko中的示例:

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

不要忘记iClickable,否则当您单击textView时,您将看不到任何内容

使用Anko实现此目的的另一种方法:

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