2011-05-19 76 views
27

是否有可能从特定主题获取样式属性值而不将主题设置为应用程序/活动? 如何获取主题属性值

+0

对于任何有兴趣的人,我自己找到解决方案:) – Kid24 2011-05-19 00:43:00

+1

TypedArray a = getTheme()。obtainStyledAttributes(R.style.ThemeName,new int [] {R.attr.attribute_name}); – Kid24 2011-05-19 00:43:57

+0

int attributeResourceId = a.getResourceId(0,0); – Kid24 2011-05-19 00:44:53

回答

39

例如(我调用context.setTheme(..)前的平均值),得到一个名为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动态看到这里:http://stackoverflow.com/a/9537629/317889 – HGPB 2013-01-24 17:25:21

+2

你应该调用['a.recycle()'](http://developer.android.com/reference/android/content/ res/TypedArray.html#recycle())完成TypedArray。 – ayke 2015-08-22 21:48:29

2

的JavaDoc:

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

R编辑一个TypedArray保存由主题定义的值,其中列出了attrs中的 。

当您完成数组时,一定要致电TypedArray.recycle()

1

如果你需要它在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,控制+点击该项目,以查看其他可能的值(文件attrs.xml将打开)。