如何获取主题属性值

34

在不设置主题到应用程序/活动之前,是否可以从特定主题获取已设置的属性值?


对于任何感兴趣的人,我已经自己找到了解决方案 :) - Kid24
1
TypedArray a = getTheme().obtainStyledAttributes(R.style.ThemeName, new int[] {R.attr.attribute_name});类型化数组 a = getTheme().obtainStyledAttributes(R.style.ThemeName, new int[]{R.attr.attribute_name}); - Kid24
int attributeResourceId = a.getResourceId(0, 0); - Kid24
2
Kid24,你可以回答自己的问题。这很有用,因为它会显示为已回答的问题。 - Cheryl Simon
1
谢谢,我会遵循你的建议,但稍后再做,因为不幸的是,“新用户在8小时内无法回答自己的问题” :) - Kid24
3
别忘了调用a.recycle() - KitKat
3个回答

49
例如,要获取名为MyTheme的主题中editTextColor属性的值:
TypedArray a = getTheme().obtainStyledAttributes(
        R.style.MyTheme,
        new int[] { R.attr.editTextColor });

// Get color hex code (eg, #fff)
int intColor = a.getColor(0 /* index */, 0 /* defaultVal */);
String hexColor = Integer.toHexString(intColor);

// Don't forget to recycle
a.recycle();

2
如果您正在寻找一种动态获取主题样式资源ID的方法,请参见此处:https://dev59.com/dWHVa4cB1Zd3GeqPjRjh#9537629 - HGPB
2
当你使用完TypedArray之后,应该调用 a.recycle() 方法。 - ayke

2

如果您需要在 XML 文件中使用它,可以使用类似以下的方式:

style="?android:attr/panelTextAppearance"

例如:
<TextView
    style="?android:attr/panelTextAppearance"
    android:paddingTop="?android:attr/paddingTop"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/your_text"
    />

如果您正在使用Eclipse,可以按住Ctrl键并单击该项,以查看其他可能的值(将打开一个名为attrs.xml的文件)。

2

JavaDoc:

方法 TypedArray android.content.res.Resources.Theme.obtainStyledAttributes(int[] attrs)

返回一个包含 Theme 中在 attrs 列表中定义的值的 TypedArray

使用完数组后一定要调用 TypedArray.recycle() 方法来回收资源。


如果不这样做会发生什么?例如,如果我离开函数作用域呢? - Sarah Multitasker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接