1


我在下面添加了 Activity,我在其中尝试创建自己的自定义 xml 字符串,
我想从中解析 ColorStateList 对象

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());
    }
}
}


尝试这样做时,我收到下一个错误:

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: 标签需要 'android:color' 属性。


调试我创建的解析器,我在属性集中看到:
attr[i] ="Android",
attr[i+1]="color",
我想我可能实例化解析器错误

4

0 回答 0