programmatically create styles in Android without referring to resources

对着背影说爱祢 提交于 2019-12-11 11:12:04

问题


I'm working on an app that reads in text from an XML document and then displays that text on the screen. I want to be able to create a TextAppearanceSpan object programmatically based on parameters given in the XML document (font, size, color, bold/italic, etc.) that don't rely on Resource files (for SpannableStrings in my TextView).

I was looking at the following constructor:

TextAppearanceSpan(String family, int style, int size, ColorStateList color, ColorStateList linkColor)

but I can't seem to find any information on how ColorStateLists work. Is what I'm trying to do even possible?


回答1:


You can look at the source code for ColorStateList here:

GrepCode: ColorStateList

For example, the following XML selector:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_focused="true" android:color="@color/testcolor1"/>
   <item android:state_pressed="true" android:state_enabled="false" android:color="@color/testcolor2" />
   <item android:state_enabled="false" android:color="@color/testcolor3" />
   <item android:color="@color/testcolor5"/>
 </selector>

is equivalent to the following code:

int[][] states = new int[4][];
int[] colors = new int[4];

states[0] = new int[] { android.R.attr.state_focused };
states[1] = new int[] { android.R.attr.state_pressed, -android.R.attr.state_enabled };
states[2] = new int[] { -android.R.attr.state_enabled };
states[3] = new int[0];

colors[0] = getResources().getColor(R.color.testcolor1);
colors[1] = getResources().getColor(R.color.testcolor2);
colors[2] = getResources().getColor(R.color.testcolor3);
colors[3] = getResources().getColor(R.color.testcolor5);

ColorStateList csl = new ColorStateList(states, colors);

The documentation for what a color state and how selectors work is here.



来源:https://stackoverflow.com/questions/14751063/programmatically-create-styles-in-android-without-referring-to-resources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!