Skip to content Skip to sidebar Skip to footer

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 ba

Solution 1:

You can look at the source code for ColorStateList here:

GrepCode: ColorStateList

For example, the following XML selector:

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

is equivalent to the following code:

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

states[0] = newint[] { android.R.attr.state_focused };
states[1] = newint[] { android.R.attr.state_pressed, -android.R.attr.state_enabled };
states[2] = newint[] { -android.R.attr.state_enabled };
states[3] = newint[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 = newColorStateList(states, colors);

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

Post a Comment for "Programmatically Create Styles In Android Without Referring To Resources"