【问题标题】:Resolving the value of "?android:attr/selectableItemBackground" in code解析代码中“?android:attr/selectableItemBackground”的值
【发布时间】:2018-04-09 19:16:16
【问题描述】:

This answer 有点帮助,但并没有完全解决我的问题。

这是我的 XML 的样子:

<android.support.v7.widget.CardView
    ... other attributes...
    android:foreground="?android:attr/selectableItemBackground"
    >

问题是我希望能够在代码中解决该属性。这是我目前所拥有的:

val typedValue = TypedValue()
context.theme.resolveAttribute(R.attr.selectableItemBackground, typedValue, true)
typedValue.string // "res/drawable/item_background_material.xml"
typedValue.type   // 3 (string)
typedValue.data   // 656

我想我可以使用链接的答案直接解析R.drawable.item_background_material,但使用?android:attr/... 的全部意义在于我不知道该属性指向何处。如何利用 TypedValue 对象中包含的信息来解析可绘制引用?

顺便说一句,我试过了

val drawableRes = string.substring(string.lastIndexOf("/") + 1, string.indexOf(".xml")) // gross, but it's just a proof of concept
val drawable = resources.getIdentifier(drawableRes, "drawable", context.packageName)

但结果总是0

【问题讨论】:

  • 查看resourceId field。即typedValue.resourceId
  • 啊哈!这完全奏效了。 val drawable = context.getDrawable(typedValue.resourceId)。如果您将其作为答案提交,我会接受。

标签: android android-custom-view


【解决方案1】:

该资源标识符将位于resourceId field 中。也就是说,在您的示例中,typedValue.resourceId

对于任何使用 Kotlin 的人来说,这是一个非常简洁的实现方式:

foreground = with(TypedValue()) {
    context.theme.resolveAttribute(R.attr.selectableItemBackground, this, true)
    ContextCompat.getDrawable(context, resourceId)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多