android - how to dynamically change color using the defined attribute -


having 2 theme, can dynamically switched.

there txtcolor attribute defined in attrs.xml

<attr name=“txtcolor” format="reference" /> 

in themes.xml, defined color attribute in different theme

<style name=“customlight" parent="apptheme.base">     <item name="txtcolor”>#000000</item>  <style name=“customdark" parent="apptheme.base">     <item name="txtcolor”>#ffffff</item> 

in layout file, using attribute fine

android:textcolor="?attr/txtcolor" 

but got exception when try use txtcolor attribute

caused by: android.content.res.resources$notfoundexception: resource id #0x7f010015 txtview.settextcolor(getresources().getcolor(r.attr.txtcolor)); 

question: how change color dynamically using attribute?

first attribute format should "color"

<attr name="txtcolor" format="color"/>

then can set color doing this:

int[] attrs = {r.attr.txtcolor} ; try { //getpackagemanager() can throw exeption     activity activity = getactivity();     themeid = activity.getpackagemanager().getactivityinfo(activity.getcomponentname(), 0).theme;     typedarray ta = activity.obtainstyledattributes(themeid, attrs);     int color = ta.getcolor(0, color.black); //i set black default color     txtview.settextcolor(color);     ta.recycle(); } catch (namenotfoundexception e) {     e.printstacktrace(); }