如何在自定义 View 上使用 selectableButtonBackground
属性,该 View 在其构造函数内使用 Anko 的 apply()
方法,如下所示的结构?
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)
但没有成功。
最佳答案
我刚刚创建了一个扩展函数来获取属性的资源 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 时你将看不到任何东西
关于android - 如何在 Anko 上使用 selectableButtonBackground?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37728702/