将字符串转换为整数并作为ID传递给视图时出现问题

时间:2010-11-16 10:49:52

标签: java android

活动中有20个按钮。

ids是R.id.ButtonR1C1; R.id.ButtonR1C2 ..依此类推。第1行,第1行......

现在我已经创建了20个按钮。

private Button b1,b2,b3...;

然后

b1=(Button)findViewbyId(R.id.ButtonR1C1);
b2=(Button)findViewbyId(R.id.ButtonR1C2);

....等等。

最后

b1.setOnClickListener(this);
b2.setOnClickListener(this);  

... 20

所以我想我会创建一个Button Array

Button barray[][]=new Button{4][5];
for(int i=1;i<=4;i++) {
   for (int j=1;j<=5;j++) {
      String t="R.id.ButtonR"+i+"C"+j;
      barray[i-1][j-1]=(Button)findViewbyId(Integer.parseInt(t));
   }
}

给出错误..

任何帮助??

5 个答案:

答案 0 :(得分:1)

如果您直接复制了代码,则语法错误。

Button barray[][]=new Button{4][5];

应该是

Button barray[][]=new Button[4][5];

请注意4之前的花括号而不是方括号。

你的下一个问题是,你试图获得R.id.something的值,但你只有它的字符串表示。所以,我知道这样做的唯一方法是使用反射。

您需要做的是,

Button barray[][]=new Button{4][5];
for(int i=1;i<=4;i++) {
   for (int j=1;j<=5;j++) {
      Class rId = R.id.getClass();
      // this gets the id from the R.id object.
      int id = rId.getField("ButtonR"+i+"C"+j).getInt(R.id);
      barray[i-1][j-1]=(Button)findViewbyId(id);
   }
}

答案 1 :(得分:0)

String t="R.id.ButtonR"+i+"C"+j;
Integer.parseInt(t);

这部分代码肯定会抛出运行时异常,因为t不包含数值。

我不知道您的ID值的格式/值,但可能会工作:

Button barray[][]=new Button[4][5];      // type corrected
for(int i=1; i<4; i++) {                   // changed the for loop...
   for (int j=1; j<5; j++) {               // changed the for loop...
      String t="R.id.ButtonR"+i+"C"+j;
      barray[i-1][j-1]=(Button)findViewbyId(t);  // t *is* the id (?)
   }
}

答案 2 :(得分:0)

问题在于:

String t="R.id.ButtonR"+i+"C"+j;
barray[i-1][j-1]=(Button)findViewbyId(Integer.parseInt(t));

您正在尝试将字符串t转换为Integer(而字符串根本不是数字)。 这将导致NumberFormatException。您应该确保t 绝对数字。

答案 3 :(得分:0)

我使用了这段代码:

Class c = Class.forName("com.test.R$id");
Integer i = new Integer(c.getField("ToolsbuttonR3C4").getInt(new R.id()));
System.out.println("HEXA="+i.toHexString(i));

并且ID按顺序排列。所以可以做到。

谢谢ppl

答案 4 :(得分:-1)

所以你试图将字符串“R.id.ButtonR1C1”转换为NUMBER ...

这肯定会给你一个NumberFormatException,因为它绝对不是一个数字! :)