FindViewById循环

时间:2012-05-16 20:54:47

标签: java android loops view

我想尝试把它放到循环中,但我似乎无法使R.id.imageView匹配。我试过:在id循环中使用string id =“R.id.imageView”+ i,但它与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);

3 个答案:

答案 0 :(得分: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()));
}

答案 1 :(得分:3)

为R.id.imageView1 ...... 12取一个整数数组并传递其值 像

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

并使用数组

答案 2 :(得分: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()));
}