我正在我的android應用中使用主題來控制哪些樣式基於清單中當前選定的主題應用於每個元素。Android - 當樣式是自定義的並且由主題控制時,以編程方式更改TextView的樣式
在任何一個主題中(其中可能會有很多),我想在運行時切換一些樣式。例如,我有一個定義文本通常應該如何顯示的樣式,另一個樣式用於定義當代碼輸入錯誤時同一段文本的外觀。
我不能直接引用@style,因爲這是由主題決定的。
我產生了一個示例應用程序來說明我的問題(注意,以下ommit的片段些零碎不相關)
Attrs.xml:(我的自定義資源的引用,所以我的佈局唐直接「T參考樣式)
<resources>
<attr name="theme_style_one" format="reference" />
<attr name="theme_style_two" format="reference" />
</resources>
的themes.xml:(選擇合適的樣式應用基於主題)
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="ThemeOne" parent="android:Theme">
<item name="theme_style_one">@style/blue</item>
<item name="theme_style_two">@style/red</item>
</style>
<style name="ThemeTwo" parent="android:Theme">
<item name="theme_style_one">@style/green</item>
<item name="theme_style_two">@style/red</item>
</style>
</resources>
Styles.xml(的風格本身)
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="blue">
<item name="android:textColor">@color/color_blue</item>
</style>
<style name="red">
<item name="android:textColor">@color/color_red</item>
</style>
<style name="green">
<item name="android:textColor">@color/color_green</item>
</style>
</resources>
Colors.xml(只是一些顏色)
<resources>
<color name="color_blue">#0000FF</color>
<color name="color_green">#00FF00</color>
<color name="color_red">#FF0000</color>
</resources>
activity_main佈局:
<TextView
android:id="@+id/txt_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world"
style="?theme_style_one" />
activity_main的onCreate:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView)findViewById(R.id.txt_text);
textView.setTextAppearance(this, R.attr.theme_style_two);
}
我想實現的是改變的TextView的風格爲 「theme_style_two」 編程。 「SetTextAppearance」命令不起作用。我無法直接在此命令中引用@ style/blue,因爲如果我在清單中更改了主題,則會應用不正確的樣式。
任何幫助將不勝感激!