SetTextAppearance through code referencing a custom attribute

I use custom attributes to implement theme switching in my application. I have the following attribute:

<resources> <attr name="TextAppearance_Footer" format="reference"></attr> </resources> 

I have two topics that define this attribute differently:

 <style name="NI_AppTheme.Dark"> <item name="TextAppearance_Footer">@style/Footer</item> </style> 

@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 in a TextView using:

 textView.setTextAppearance(this, R.attr.TextAppearance_Footer); 

This does not work (i.e. does not set the text to green). However, if I specify the appearance of the text through xml using:

 android:textAppearance="?TextAppearance_Footer" 

It works great. What can i skip? I need to set attributes, because I want to dynamically switch between themes.

Additional Information:

If I use:

 textView.setTextAppearance(this, R.style.NI_AppTheme.Dark); 

Everything seems to be in order.

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); } 
+5
source share
1 answer

Why not use:

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

I think textAppearance should be a style.

Edit:

Maybe you should try:

 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: Correctly 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); } 
+11
source

Source: https://habr.com/ru/post/918740/


All Articles