【问题标题】:Dynamically assign a value through loop - Android - Programmatically by java通过循环动态分配值 - Android - 由 java 以编程方式
【发布时间】:2017-01-01 16:22:16
【问题描述】:

这里是定制的圆形图像列表。需要通过循环动态赋值。

            RoundedImageView img23 = (RoundedImageView) findViewById(R.id.avatar23);
            img23.setImageResource(R.mipmap.avatars_male_28);

            RoundedImageView img24 = (RoundedImageView) findViewById(R.id.avatar24);
            img24.setImageResource(R.mipmap.avatars_male_29);

            RoundedImageView img25 = (RoundedImageView) findViewById(R.id.avatar25);
            img25.setImageResource(R.mipmap.avatars_male_30);

            for (i = 1;i>25; i++){
                j=(String) i;

                //need a loop that dynamically sets img**2** (any number)
                img<j>.setImageResource(R.mipmap.avatars_male_30);
            }

【问题讨论】:

  • 将图像添加到列表或数组中?
  • 创建一个列表List&lt;RoundedImageView&gt;,然后迭代您的列表。简单,快速:)

标签: java android loops variables dynamic


【解决方案1】:

而不是创建 RoundedImageView img1, RoundedImageView img2, RoundedImageView img3 ...

只需创建一个 RoundImageView 的 ArrayList:

ArrayList<RoundedImageView> list = new ArrayList<RoundedImageView>();
list.add((RoundedImageView) findViewById(R.id.avatar1));
list.add((RoundedImageView) findViewById(R.id.avatar2));
list.add((RoundedImageView) findViewById(R.id.avatar3));

。 . .

【讨论】:

    【解决方案2】:

    你可以通过制作 imageview 类型模型然后从模型中提取 imageview 并将你的 drawables 使用到 imageview 中来做这样的......

        //You can make ImageViewModel type class there you save your image view
         class ImageViewModel {
    
            public ImageView getImage() {
                return image;
            }
    
            public void setImage(ImageView image) {
                this.image = image;
            }
    
            ImageView image;
    
        }
        ArrayList<ImageViewModel> images = new ArrayList<>();
        ArrayList<Integer> drawables = new ArrayList<>();
        drawables.add(R.mipmap.ic_launcher);
        drawables.add(R.mipmap.ic_launcher);
        drawables.add(R.mipmap.ic_launcher);
    
    
    
        //set you imageview in model class and add into the arraylist of modelclass type
        ImageViewModel model = new ImageViewModel();
        model.setImage(imageviews);
        images.add(model);
    
    
    
    
       // Then you can set this as
        for(int i = 0; i<drawables.size(); i++){
    
             model.getImage().setImageResource(drawables.get(i));
        }
    

    因此您可以将图像动态设置为 Imageview

    这对我有用,可能对你也有用

    【讨论】:

      【解决方案3】:

      要删除所有这些样板代码,请使用黄油刀库http://jakewharton.github.io/butterknife/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-12
        • 1970-01-01
        • 2012-12-23
        • 1970-01-01
        • 2012-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多