2013-06-24 35 views
48

考慮一下:獲取顏色值編程時,這是一個參考(主題)

styles.xml

<style name="BlueTheme" parent="@android:style/Theme.Black.NoTitleBar"> 
    <item name="theme_color">@color/theme_color_blue</item> 
</style> 

attrs.xml

<attr name="theme_color" format="reference" /> 

color.xml

<color name="theme_color_blue">#ff0071d3</color> 

所以主題顏色被引用的主題。我怎樣才能以編程方式獲得theme_color(引用)?通常我會使用getResources().getColor(),但在這種情況下不會使用,因爲它被引用了!

回答

126

這應該做的工作:

TypedValue typedValue = new TypedValue(); 
Theme theme = context.getTheme(); 
theme.resolveAttribute(R.attr.theme_color, typedValue, true); 
@ColorInt int color = typedValue.data; 

另外,還要確保在調用此代碼前將主題應用到您的活動。無論是使用:

android:theme="@style/Theme.BlueTheme" 
在清單或電話

(你叫setContentView(int)前):

setTheme(R.style.Theme_BlueTheme) 
onCreate()

我已經用你的值測試過它,它工作完美。

+0

謝謝我不能嘗試你的解決方案,但因爲我得到一個錯誤:http://stackoverflow.com/questions/17278244/cant-use-referenced-color-by-theme-in-drawable麻你有這方面的經驗... –

+2

無論如何,用你的解決方案,我得到一個0值的顏色(TypedValue {t = 0x0/d = 0x0})...我不使用declare-styleable,只是對顏色的引用 –

+1

resolveAttribute()返回false –

15

這爲我工作:

int[] attrs = {R.attr.my_attribute}; 
TypedArray ta = context.obtainStyledAttributes(attrs); 
int color = ta.getResourceId(0, android.R.color.black); 
ta.recycle(); 

,如果你想獲得比特產出來的:

Integer.toHexString(color) 
+6

需要「回收」數組,否則這與任何答案一樣好。 – roide

1

如果你想獲得多種顏色,你可以使用:

int[] attrs = {R.attr.customAttr, android.R.attr.textColorSecondary, 
     android.R.attr.textColorPrimaryInverse}; 
Resources.Theme theme = context.getTheme(); 
TypedArray ta = theme.obtainStyledAttributes(attrs); 

int[] colors = new int[attrs.length]; 
for (int i = 0; i < attrs.length; i++) { 
    colors[i] = ta.getColor(i, 0); 
} 

ta.recycle();