bibismcbryde
bibismcbryde

Reputation: 459

programmatically create styles in Android without referring to resources

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?

Upvotes: 0

Views: 1553

Answers (1)

Marius
Marius

Reputation: 286

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.

Upvotes: 3

Related Questions