【问题标题】:Can I put this into a for loop? [duplicate]我可以把它放到一个for循环中吗? [复制]
【发布时间】:2011-09-26 18:44:10
【问题描述】:

可能重复:
android: how to elegantly set many button IDs

这是一个用eclipse制作的android程序。我尝试使用字符串连接代替 imageButton1 无济于事。 R 是生成的类,所以我不能进入它并编辑它,以便 imageButtons 是数组的一部分。 如何将其放入 for 循环中?

    seatButton[0] = (ImageButton) findViewById(R.id.imageButton1);
    seatButton[1] = (ImageButton) findViewById(R.id.imageButton2);
    seatButton[2] = (ImageButton) findViewById(R.id.imageButton3);
    seatButton[3] = (ImageButton) findViewById(R.id.imageButton4);
    seatButton[4] = (ImageButton) findViewById(R.id.imageButton5);
    seatButton[5] = (ImageButton) findViewById(R.id.imageButton6);
    seatButton[6] = (ImageButton) findViewById(R.id.imageButton7);
    seatButton[7] = (ImageButton) findViewById(R.id.imageButton8);
    seatButton[8] = (ImageButton) findViewById(R.id.imageButton9);
    seatButton[9] = (ImageButton) findViewById(R.id.imageButton10);

【问题讨论】:

标签: java android eclipse for-loop r.java-file


【解决方案1】:

可以,一种方法如下:

ImageButton[] btns = {R.id.imageButton1, R.id.imageButton2, ..., R.id.imageButton10};
for(int i = 0, len = btns.length; i < len; i++) {
    seatButton[i] = (ImageButton) findByViewId(btns[i]);
}

【讨论】:

    【解决方案2】:

    您也可以使用getResources().getIdentifier(String name, String defType, String defPackage),其中 name 是资源名称,defType 是可绘制的,而 defPackage 是您的完整包名称。 这将导致类似:

    for (int i = 0; i < 10; i++) {
        int resId = getResources().getIdentifier("imageButton" + (i + 1), "id", your_package");
        seatButton[i] = (ImageButton) findViewById(resId);
    }
    

    【讨论】:

      【解决方案3】:

      我对您的应用程序或 android 一无所知,但您可以使用运行时反射(尽管在我看来,如果可以避免,则不应使用它)。

      import java.lang.reflect.Field;
      
      ...
      
      for(int i=1; ; i++) {
          try {
              Field f = R.id.getClass().getField("imageButton" + i);
              seatButton[i-1] = (ImageButton) findByViewId(f.get(R.id)); // Add cast to whatever type R.id.imageButton<i> is
          } catch (Exception e) {
              break;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-28
        • 1970-01-01
        • 1970-01-01
        • 2014-03-01
        相关资源
        最近更新 更多