setTextAppearance通过代码引用自定义属性

Cod*_*oet 5 android

我正在使用自定义属性在我的应用程序中实现主题切换.我定义了以下属性:

<resources>
    <attr name="TextAppearance_Footer" format="reference"></attr>
</resources>
Run Code Online (Sandbox Code Playgroud)

我有两个主题,以不同的方式定义此属性:

<style name="NI_AppTheme.Dark">
    <item name="TextAppearance_Footer">@style/Footer</item>
</style>
Run Code Online (Sandbox Code Playgroud)

@style/Footer定义如下:

<style name="Footer" parent="@android:style/TextAppearance.Large">
    <item name="android:textColor">#00FF00</item> // Green
</style>
Run Code Online (Sandbox Code Playgroud)

现在,如果我尝试将此样式设置为TextView使用:

textView.setTextAppearance(this, R.attr.TextAppearance_Footer);
Run Code Online (Sandbox Code Playgroud)

它不起作用(即不将文本设置为绿色).但是,如果我使用xml通过xml指定文本外观:

android:textAppearance="?TextAppearance_Footer"
Run Code Online (Sandbox Code Playgroud)

它工作正常.我能错过什么?我需要设置属性,因为我想动态地在主题之间切换.

附加信息:

如果我使用:

textView.setTextAppearance(this, R.style.NI_AppTheme.Dark);
Run Code Online (Sandbox Code Playgroud)

它似乎工作正常.

编辑:经过测试的工作解决方案(感谢@nininho):

Resources.Theme theme = getTheme();
TypedValue styleID = new TypedValue();
if (theme.resolveAttribute(R.attr.Channel_Title_Style, styleID, true)) {
     channelTitle.setTextAppearance(this, styleID.data);
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*vre 11

为什么不使用:

textView.setTextAppearance(this, R.style.Footer);
Run Code Online (Sandbox Code Playgroud)

我认为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);
Run Code Online (Sandbox Code Playgroud)

编辑: 正确的测试代码:

Resources.Theme theme = getTheme();
TypedValue styleID = new TypedValue();
if (theme.resolveAttribute(R.attr.Channel_Title_Style, styleID, true)) {
     channelTitle.setTextAppearance(this, styleID.data);
}
Run Code Online (Sandbox Code Playgroud)