據我所知,你在談論使用多個主題。這是您的問題的場景。
定義兩個主題在styles.xml
主題藍:
<style name="AppTheme.Blue" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/primaryColor_blue</item>
<item name="colorPrimaryDark">@color/primaryColorDark_blue</item>
<item name="colorAccent">@color/primaryAccent_blue</item>
<item name="backgroundColor">@color/primaryColorDark_blue</item>
</style>
主題綠色:
<style name="AppTheme.Green" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/primaryColor_green</item>
<item name="colorPrimaryDark">@color/primaryColorDark_green</item>
<item name="colorAccent">@color/primaryAccent_green</item>
<item name="backgroundColor">@color/primaryColorDark_green</item>
</style>
定義在color.xml所有的顏色也會相應
添加以下代碼獲取所選主題的主要顏色並將其設置爲您的窗口小部件。
TypedValue typedValue = new TypedValue();
Resources.Theme theme = this.getTheme();
theme.resolveAttribute(android.R.attr.textColorPrimary, typedValue, true);
TypedArray arr =
this.obtainStyledAttributes(typedValue.data, new int[]{
android.R.attr.colorPrimary});
int primaryColor = arr.getColor(0, -1);
yourTextView.setTextColor(primaryColor); //ex
arr.recycle();
如果您選擇的主題是藍色,那麼textcolor也是藍色的。希望這足夠。
這似乎是一個不錯的解決方案,首先謝謝。而且我還有一個問題是,使用'obtainStyledAttributes'會有很大的效率損失,如果是的話,我最好創建一個Hashmap或其他顏色的緩存。 – AsyncCode
只要你回收你的TypedArray,它不應該是一個問題 – tahsinRupam