1


I have the Activity added below, in which I try to create my own custom xml string,
Which from I want to parse a ColorStateList object

public class MainActivity extends Activity {

final String colorVals = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + 
        "<selector xmlns:android=\"http://schemas.android.com/apk/res/android\">" +
   "<item android:color=\"#333\" android:state_focused=\"true\" />" +
   "<item android:color=\"#fff\" android:state_pressed=\"true\" />" +
   "<item android:color=\"#666\" android:state_enabled=\"false\" />" +
   "<item android:color=\"#222\"/>" +
 "</selector>";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try {

        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(true);
        XmlPullParser parser = factory.newPullParser();
        String xml = colorVals;
        InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));

        parser.setInput(is, "UTF-8");
        Resources res = getResources();
        ColorStateList colors = ColorStateList.createFromXml(res, parser);
        TextView tv = new TextView(this);
        tv.setTextColor(colors);
    } catch (Exception e) {
        Log.e("test", e.getMessage());
    }
}
}


when trying to do so I get the next error:

10-22 16:23:04.006: E/test(16127): START_TAG (empty) http://schemas.android.com/apk/res/android}android:color='#333' {http://schemas.android.com/apk/res/android}android:state_focused='true'>@1:166 in java.io.InputStreamReader@41dcc110: tag requires a 'android:color' attribute.


Debugging the parser that I have created, I see in the attribute set:
attr[i] ="Android",
attr[i+1]="color",
I think I might be instantiating the parser wrong

Elad Gelman
  • 1,182
  • 1
  • 13
  • 27
  • why do you parse xml data ? – pskink Oct 22 '13 at 13:40
  • @psking In order to create a ColorStateList from code I have two options as I see it, 1. create the ColorStateList from a combination of colors and states like [here](http://stackoverflow.com/questions/14751063/programmatically-create-styles-in-android-without-referring-to-resources) for example 2. parse a string that I can manipulate at runtime, and the android SDK will handle the rest.. – Elad Gelman Oct 22 '13 at 13:49
  • and the first option is a valid one – pskink Oct 22 '13 at 14:03
  • you **meant** is **the** valid one? – Elad Gelman Oct 22 '13 at 14:07
  • yes, use ColorStateList ctor – pskink Oct 22 '13 at 14:13
  • This problem list ways to create a color state list programmatically: https://stackoverflow.com/questions/15543186/how-do-i-create-colorstatelist-programmatically/35614572 – ThomasW Dec 26 '18 at 05:21

0 Answers0