Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

android - setTextAppearance through code referencing custom attribute

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why not use:

textView.setTextAppearance(this, R.style.Footer);

I think that the textAppearance must be a style.

Edit:

Maybe you should try this:

TypedArray a = context.obtainStyledAttributes(attrs,
new int[] { R.attr.TextAppearance_Footer });

int id = a.getResourceId(R.attr.TextAppearance_Footer, defValue);
textView.setTextAppearance(this, id);

EDIT: Correct Tested Code:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...