android - 如何在 Anko 上使用 selectableButtonBackground?

标签 android kotlin anko

如何在自定义 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/

相关文章:

android - 如何获取选定的文本和值 Android ListPreference

android - 我如何在RecyclerView Adapter中获得第二个模型的位置

android - 有没有办法在 fragment 中使用Anko commons?

java - 在MainActivity java中,如何直接调用anko类?

java - 如何从 Firebase 实时数据库引用中重复获取值?

android - 了解可用屏幕宽度与最小宽度

java - 在android中用字符串中的另一个字符替换一个字符?

android - 用于 kotlin 的 Android 中的静态等效项,以避免处理程序内存泄漏

android-studio - "Include Kotlin support"复选框不在 Android Studio 3.0 Canary 5

android - 如何将 MutableMap<String, Any?> 转换为 vararg 值 : Pair<String, Any?>?