代码之家  ›  专栏  ›  技术社区  ›  AutonomousApps

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

  •  2
  • AutonomousApps  · 技术社区  · 7 年前

    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

    1 回复  |  直到 7 年前
        1
  •  1
  •   AutonomousApps    7 年前

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

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

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