2013-07-30 46 views
0

我从Catch The Cows下载了class,它类似于Google Map对象,或者至少这就是我正在使用的对象。以编程方式设置R.ID

它解析一个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

嘛,个人,该代码是如此格式不我觉得很难看,更别说搞清楚什么是应该做的。请给我们一个正确格式化的机会。 – Simon

+0

已经完成 - 我已经点击块评论,而不是意外的代码部分。 –

+0

在'Resources'类中,您有'getIdentifier()'方法,您可以通过它获取''id''“名称”:'getIdentifier(“id”,“area10”,context.getPackage())''。 – Luksprog

回答

1

R是一个只读类。它是在编译时生成的,您不应该使用反射来修改其字段。你也应该避免反射来访问字段值。你应该使用官方的API。

在类的第一行注释是

/* AUTO-GENERATED FILE. DO NOT MODIFY. */ 
+0

这是我下载的类中的代码,它不起作用。我试图解决的是实际上正在做的事情,以便我可以重做它。 –

+0

你想要达到什么 – Blackbelt

+0

作为下面的答案 - 格式化 –