I am using custom attributes to implement theme switching in my application. I have the following attribute defined:
<resources>
<attr name="TextAppearance_Footer" format="reference"></attr>
</resources>
I have two themes which define this attribute differently:
<style name="NI_AppTheme.Dark">
<item name="TextAppearance_Footer">@style/Footer</item>
</style>
The @style/Footer
is defined as follows:
<style name="Footer" parent="@android:style/TextAppearance.Large">
<item name="android:textColor">#00FF00</item> // Green
</style>
Now if I try to set this style to a TextView
using:
textView.setTextAppearance(this, R.attr.TextAppearance_Footer);
It does not work (i.e. does not set the text to Green). However, if I specify the text appearance via xml using:
android:textAppearance="?TextAppearance_Footer"
It works fine. What could I be missing? I need to set the attributes because I want to dynamically be able to switch between themes.
Additional Info:
If I use:
textView.setTextAppearance(this, R.style.NI_AppTheme.Dark);
It seems to work all right.
EDIT: Tested Working Solution (thanks @nininho):
Resources.Theme theme = getTheme();
TypedValue styleID = new TypedValue();
if (theme.resolveAttribute(R.attr.Channel_Title_Style, styleID, true)) {
channelTitle.setTextAppearance(this, styleID.data);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…