如何以编程方式获取 ?attr/ 值

Gra*_*eme 6 android android-styles

我正在尝试做一些自定义视图样式,但在从主题中正确选择样式属性时遇到了问题。

例如,我想获得主题 EditText 的文本颜色。

查看主题堆栈,您可以看到我的主题使用它来设置它的 EditText 样式:

<style name="Base.V7.Widget.AppCompat.EditText" parent="android:Widget.EditText">
    <item name="android:background">?attr/editTextBackground</item>
    <item name="android:textColor">?attr/editTextColor</item>
    <item name="android:textAppearance">?android:attr/textAppearanceMediumInverse</item>
</style>
Run Code Online (Sandbox Code Playgroud)

我正在寻找的是我如何得到那个? attr/editTextColor

(又名,主题分配给“android:editTextColor”的值)

通过谷歌搜索,我找到了足够的答案:

TypedArray a = mView.getContext().getTheme().obtainStyledAttributes(R.style.editTextStyle, new int[] {R.attr.editTextColor});
int color = a.getResourceId(0, 0);
a.recycle();
Run Code Online (Sandbox Code Playgroud)

但我很确定我一定是做错了,因为它总是显示为黑色而不是灰色?

Gra*_*eme 9

正如@pskink 所评论的:

    TypedValue value = new TypedValue();
    getContext().getTheme().resolveAttribute(android.R.attr.editTextColor, value, true);
    getView().setBackgroundColor(value.data);
Run Code Online (Sandbox Code Playgroud)

将从当前分配给上下文的主题中提取属性。

谢谢@pskink!

  • Muthukrishnan - 我拒绝通过混淆未来的观众而不增加价值而降低价值的答案。它没有反映我对答案作者的看法,我感谢他们的尝试和他们花费的时间。投票是我们作为 SO 用户管理内容的方式 - 它的功能不是惩罚用户。 (3认同)