我正在使用自定义属性在我的应用程序中实现主题切换。我定义了以下属性:
<resources>
<attr name="TextAppearance_Footer" format="reference"></attr>
</resources>
我有两个主题,它们以不同的方式定义此属性:
<style name="NI_AppTheme.Dark">
<item name="TextAppearance_Footer">@style/Footer</item>
</style>
@style/Footer
的定义如下:
<style name="Footer" parent="@android:style/TextAppearance.Large">
<item name="android:textColor">#00FF00</item> // Green
</style>
现在,如果我尝试使用以下方式将此样式设置为TextView
textView.setTextAppearance(this, R.attr.TextAppearance_Footer);
它不起作用(即不将文本设置为绿色)。但是,如果我使用以下命令通过xml指定文本外观:
android:textAppearance="?TextAppearance_Footer"
工作正常。我能错过什么?我需要设置属性,因为我想动态地在主题之间切换。
其他信息:
如果我使用:
textView.setTextAppearance(this, R.style.NI_AppTheme.Dark);
似乎工作正常。
编辑:经过测试的工作解决方案(感谢@nininho):
Resources.Theme theme = getTheme();
TypedValue styleID = new TypedValue();
if (theme.resolveAttribute(R.attr.Channel_Title_Style, styleID, true)) {
channelTitle.setTextAppearance(this, styleID.data);
}
答案 0 :(得分:11)
为什么不使用:
textView.setTextAppearance(this, R.style.Footer);
我认为textAppearance必须是一种风格。
编辑:
也许你应该试试这个:
TypedArray a = context.obtainStyledAttributes(attrs,
new int[] { R.attr.TextAppearance_Footer });
int id = a.getResourceId(R.attr.TextAppearance_Footer, defValue);
textView.setTextAppearance(this, id);
修改强> 正确的测试代码:
Resources.Theme theme = getTheme();
TypedValue styleID = new TypedValue();
if (theme.resolveAttribute(R.attr.Channel_Title_Style, styleID, true)) {
channelTitle.setTextAppearance(this, styleID.data);
}