1

我想尝试将其放入循环中,但我似乎无法使 R.id.imageView 匹配。我试过:string id = "R.id.imageView"+i 在 for 循环中,但它与 findViewById 的参数不匹配。有任何想法吗?非常感谢任何帮助。

   buttons[0] = (ImageView) this.findViewById(R.id.imageView1);
   buttons[1] = (ImageView) this.findViewById(R.id.imageView2);
   buttons[2] = (ImageView) this.findViewById(R.id.imageView3);
   buttons[3] = (ImageView) this.findViewById(R.id.imageView4);
   buttons[4] = (ImageView) this.findViewById(R.id.imageView5);
   buttons[5] = (ImageView) this.findViewById(R.id.imageView6);
   buttons[6] = (ImageView) this.findViewById(R.id.imageView7);
   buttons[7] = (ImageView) this.findViewById(R.id.imageView8);
   buttons[8] = (ImageView) this.findViewById(R.id.imageView9);
   buttons[9] = (ImageView) this.findViewById(R.id.imageView10);
   buttons[10] = (ImageView) this.findViewById(R.id.imageView11);
   buttons[11] = (ImageView) this.findViewById(R.id.imageView12);
4

3 回答 3

3

使用getIdentifier()方法:

Resources res = getResources(); //if you are in an activity
for (int i = 1; i < 13; i++) {
   String idName = "imageView" + i;
   buttons[i] = (ImageView) findViewById(res.getIdentifier(idName, "id, getPackageName()));
}
于 2012-05-16T20:59:48.647 回答
3

为 R.id.imageView1......12 取一个整数数组并传递它的值 Like

private Integer[] Imgid = {R.id.imageview1,....,12  };

并使用数组

于 2012-05-16T21:00:26.073 回答
1

与上面相同,只是错字已修复。似乎比“最佳答案”更好,因为如果您不需要它,您不必定义任何数组。

Resources res = getResources(); //if you are in an activity
for (int i = 1; i < 13; i++) {
  String idName = "imageView" + i;
  imageViews[i] = (ImageView) findViewById(res.getIdentifier(idName, "id", getPackageName()));
}
于 2015-01-13T12:08:02.487 回答