2012-09-11 32 views
26

我想是這樣的,但我堅持:如何從當前主題獲得背景色編程

TypedValue typedValue = new TypedValue(); 
if (this.parentActivity.getTheme().resolveAttribute(android.R.attr.windowBackground, typedValue, true)) 
{ 
    // how to get color? 
} 
+9

在XML機器人:背景= 「機器人:ATTR/colorBackground」 – ademar111190

+2

我測試和確定'機器人:?ATTR/colorBackground'對應於'styles.xml'項'<項目名稱=「機器人:colorBackground「> @ color/yourColorHere'。 –

+0

@ ademar111190這應該是答案! – Alexandr

回答

52

你可以得到從當前主題背景顏色(或可繪製)通過:

TypedValue a = new TypedValue(); 
getTheme().resolveAttribute(android.R.attr.windowBackground, a, true); 
if (a.type >= TypedValue.TYPE_FIRST_COLOR_INT && a.type <= TypedValue.TYPE_LAST_COLOR_INT) { 
    // windowBackground is a color 
    int color = a.data; 
} else { 
    // windowBackground is not a color, probably a drawable 
    Drawable d = activity.getResources().getDrawable(a.resourceId); 
} 
+2

偉大的答案。萬一別人是通過這個絆倒,在Xamarin,你必須使用Resource.Attribute.primaryAccentColor代替,例如,Resource.Styleable.MyTheme_primaryAccentColor。這也可能適用於Android本機開發。也就是說,直接引用attr文件/對象而不是主題。我不理解上的差異,但後者似乎將是正確的選擇,但並非如此。 – pbarranis

4

您可以通過使用讓您的主題的資源:

TypedArray a = getTheme().obtainStyledAttributes(R.style.ThemeName, new int[] {R.attr.attribute_name});  
int attributeResourceId = a.getResourceId(0, 0); 
+0

我試過這個:TypedArray a = this.parentActivity.getTheme()。obtainStyledAttributes(android.R.attr.windowBackground,new int [] {android.R.attr.windowBackground}); \t \t int attributeResourceId = a.getResourceId(0,0); \t \t \t \t int aaa = this.parentActivity.getResources()。getColor(attributeResourceId);但這不起作用。我得到例外。 –

+0

哦!你會得到什麼例外? – Swayam

+0

09-12 12:05:34.864:E/AndroidRuntime(32137):致命異常:主要 09-12 12:05:34.864:E/AndroidRuntime(32137):android.content.res.Resources $ NotFoundException:File res /drawable/screen_background_selector_light.xml來自顏色狀態列表資源ID#0x10804a8 09-12 12:05:34.864:E/AndroidRuntime(32137):\t at android.content.res.Resources.loadColorStateList(Resources.java) 09- 12 12:05:34.864:E/AndroidRuntime(32137):\t at android.content.res.Resources.getColor(Resources.java)... –

1

爲您的qoustion最簡單的方法是:

TypedValue typedValue = new TypedValue(); 
if (this.parentActivity.getTheme().resolveAttribute(android.R.attr.windowBackground, typedValue, true)) 
{ 
    // how to get color? 
    int colorWindowBackground = typedValue.data;// **just add this line to your code!!** 
} 
相關問題