2

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

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

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

我试过做,context.obtainStyledAttributes(arrayOf(R.attr.selectableItemBackground).toIntArray()).getDrawable(0)但没有成功。

4

2 回答 2

2

我刚刚创建了一个扩展函数来获取属性的资源 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
   }
}

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

于 2016-12-01T12:17:33.660 回答
0

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

val backgroundResource = attr(R.attr.selectableItemBackgroundBorderless).resourceId
于 2019-03-25T14:41:16.870 回答