【问题标题】:"findViewById" with for loop [duplicate]带有for循环的“findViewById”[重复]
【发布时间】:2015-04-10 11:22:05
【问题描述】:

这是我的代码:

ImageView img1 = (ImageView) findViewById(R.id.img1);
ImageView img2 = (ImageView) findViewById(R.id.img2);
ImageView img3 = (ImageView) findViewById(R.id.img3);
ImageView img4 = (ImageView) findViewById(R.id.img4);
ImageView img5 = (ImageView) findViewById(R.id.img5);
ImageView img6 = (ImageView) findViewById(R.id.img6);
ImageView img7 = (ImageView) findViewById(R.id.img7);
ImageView img8 = (ImageView) findViewById(R.id.img8);
ImageView img9 = (ImageView) findViewById(R.id.img9);

我想创建这样的东西:

     for (int i=1; i<=9; i++) { 
ImageView img+i = (ImageView) findViewById(R.id.img+i);}

我该怎么做?

【问题讨论】:

  • 你熟悉数组吗?

标签: android for-loop findviewbyid


【解决方案1】:

这样做。您可以从存储在 xml 或代码中的数组中获取可绘制名称。

for (int i=1; i<=9; i++) { 

int id = getResources().getIdentifier("drawableName", "drawable", context.getPackageName());

ImageView img = (ImageView) findViewById(id);
}

这里的“drawableName”是你的图像的名称,保持“drawable”不变。

【讨论】:

    【解决方案2】:

    您不能在循环中执行此操作。 基本上 R.id.img 是一个整数,并且 如果你做 R.id.img + i,它会产生一些随机整数。

    【讨论】:

      猜你喜欢
      • 2013-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多