如何在Anko上使用selectableButtonBackground?
如何在像下面的结构一样的构造函数中使用Anko的apply()
方法的自定义View上使用selectableButtonBackground
属性?
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时你将看不到任何东西