我从class下载了Catch The Cows,它类似于谷歌地图对象,或者至少是我使用它的目的。
它解析一个XML文件,该文件列出了应该可触摸的屏幕区域,然后使用此方法创建它们。 这是针对上下文的,我已经注释了代码的某些部分,并添加了我自己的代码以尝试解决我的问题
private Area addShape( String shape, String name, String coords, String id) {
Log.v("IDS:", "id was "+id);
Area a = null;
String rid = id.replace("@+id/", "");
Log.v("IDS:", "rid was "+rid);
// Generate a new ID for the area.
int _id = 1;
View vi = findViewById(_id);
while (vi!=null) {
_id++;
vi = findViewById(_id);
}
//View.generateViewId(); //=0;
Log.v("IDS:", "After conversion final time "+_id);
/*
try {
Class<R.id> res = R.id.class;
Field field = res.getField(rid); // eg. rid = area10
_id = field.getInt(null);
Log.v("IDS:", "After conversion "+_id);
}
catch (Exception e) {
_id = 0;
Log.e("Exception ",e.getMessage());
} finally {
Log.v("IDS:", "After conversion final time "+_id);
}
*/
if (_id != 0) {
if (shape.equalsIgnoreCase("rect")) {
String[] v = coords.split(",");
if (v.length == 4) {
a = new RectArea(_id, name, Float.parseFloat(v[0]),
Float.parseFloat(v[1]),
Float.parseFloat(v[2]),
Float.parseFloat(v[3]));
}
}
if (shape.equalsIgnoreCase("circle")) {
String[] v = coords.split(",");
if (v.length == 3) {
a = new CircleArea(_id,name, Float.parseFloat(v[0]),
Float.parseFloat(v[1]),
Float.parseFloat(v[2])
);
}
}
if (shape.equalsIgnoreCase("poly")) {
a = new PolyArea(_id,name, coords);
}
if (a != null) {
addArea(a);
}
} else {
Log.v("Loading ID: ","_id was 0");
}
return a;
}
不幸的是,屏幕上没有渲染,这是因为_id = 0.这应该用这段代码改变:
try {
Class<R.id> res = R.id.class;
Field field = res.getField(rid); // eg. rid = area10
_id = field.getInt(null);
}
我怎么不知道尝试和调试它做了什么,任何人都可以解释这个片段在做什么吗?
答案 0 :(得分:1)
R是只读类。它是在编译时生成的,您不应该使用反射来修改其字段。您还应该避免反射来访问字段值。您应该使用官方API。
班级第一行的评论是
/* AUTO-GENERATED FILE. DO NOT MODIFY. */