解析代码中“?android:attr/selectableItemBackground”的值

Resolving the value of "?android:attr/selectableItemBackground" in code

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

这是我的 XML 的样子:

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

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

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.

对于任何使用 Kotlin 的人来说,这里有一个非常巧妙的实现方式:

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