【问题标题】:Getting views from ResourceIDs in for loop在 for 循环中从 ResourceID 获取视图
【发布时间】:2014-03-29 17:37:04
【问题描述】:

看下面的android代码。

    iv11 = (ImageView) findViewById(R.id.immg11);
    iv12 = (ImageView) findViewById(R.id.immg12);
    iv13 = (ImageView) findViewById(R.id.immg13);
    iv14 = (ImageView) findViewById(R.id.immg14);
    iv15 = (ImageView) findViewById(R.id.immg15);
    iv16 = (ImageView) findViewById(R.id.immg16);

6ImageView 变量以上分配6 图像。实际上,我必须为 36 个变量执行此操作。是否可以使用某种for 循环来完成这种分配?

【问题讨论】:

  • 您可以使用 List 而不是 36 个 ivXX 变量。
  • 我认为你应该通过代码创建 ImageView。或者,更好的是,使用列表广告@juan.facorro 说

标签: java android variable-assignment


【解决方案1】:

如果您的所有 ImageView 都在 相同的布局,那么使用此代码您可以获得 id 和 ImageViews 的列表。如果它们不在同一布局中,则需要使用嵌套循环。

ArrayList<ImageView> imageList=new ArrayList<ImageView>();
ArrayList<Integer> idList=new ArrayList<Integer>();
LinearLayout ll;

ll=(LinearLayout)findViewById(R.id.layout);

for(int i=0;i<ll.getChildCount();i++){
        View v=ll.getChildAt(i);
        if(v instanceof ImageView){
            imageList.add((ImageView)v);
            idList.add(v.getId());
        }
 }

更新在你的情况下,我建议你应该使用这样的嵌套循环

TableLayout tl;

tl=(TableLayout)findViewById(R.id.layout);

for(int i=0;i<tl.getChildCount();i++){
    View v=tl.getChildAt(i);
if(v instanceof TableRow){

    for(int j=0;j<v.getChildCount();j++){
      View innerView=v.getChildAt(j);
      if(innerView instanceof ImageView){
        imageList.add((ImageView)innerView);
        idList.add(innerView.getId());
       }
    } 
 }

}

【讨论】:

  • 但它是6行6列的表格布局
【解决方案2】:

您可以使用 RoboGuice 之类的工具来缩短代码,但不必告诉 Android 哪个视图 id 映射到哪个对象。

https://github.com/roboguice/roboguice/wiki

【讨论】:

    【解决方案3】:

    您可以为图像值变量 (iv##) 执行此操作,但您不能为 R 生成的 int id (R.id.immg##) 执行此操作,因为它们是自动生成的随机十六进制,并且因此,无论如何您都必须手动分配它们,并且不能迭代它们。

    要将字符串转换为变量,您只需要使用(在这种情况下)Integer.parseInt(string) 并且根据您想要的数字类型,它会有所不同。

    【讨论】:

      【解决方案4】:

      我的项目代码:

      for( Field f : R.layout.class.getFields() ){
        if( f.getName().startsWith( "image" ) ){
          try{
            IMAGE_MAP.put( f.getName().substring( 4 ).toLowerCase(), f.getInt( null ) );
          }catch( IllegalArgumentException e ){
          }catch( IllegalAccessException e ){}
        }
      }
      

      【讨论】:

      • 需要指出的是,这段代码使用了反射,这对性能有很大的影响。以防 OP 发布的代码位于性能至关重要的位置。
      • 你高估了反射成本,尤其是当它必须为一个活动或整个应用只调用一次时
      猜你喜欢
      • 1970-01-01
      • 2020-02-21
      • 1970-01-01
      • 2015-06-13
      • 2011-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多