Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTextAppearance through code referencing custom attribute

Tags:

android

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);
}
like image 926
Code Poet Avatar asked Jan 06 '12 12:01

Code Poet


1 Answers

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);
}
like image 79
Marcio Covre Avatar answered Sep 19 '22 00:09

Marcio Covre