繁体   English   中英

以编程方式添加视图,并在添加按钮后单击更改视图背景

[英]Add View programmatically and after adding on button click change view background

在 LinearLayout 中动态添加视图,并在添加视图后更改单击按钮上的任何视图背景。

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, height);
ImageView img1 = new ImageView(this);
img1.setLayoutParams(layoutParams);
img1.setImageBitmap(icon);
llLayout.addView(img1);

ImageView img2 = new ImageView(this);
img2.setLayoutParams(layoutParams);
img2.setImageBitmap(icon);
llLayout.addView(img2);

ImageView img3 = new ImageView(this);
img3.setLayoutParams(layoutParams);
img3.setImageBitmap(icon);
llLayout.addView(img3);   

在按钮上,单击更改所有 imageview 背景或特定 ImageView。

注意: llLayout是我的线性布局这个布局在XML中加入

当您将 imageView 添加到线性布局中时,此时您将setImageBitmap设置为 imageView。

如果你想将图像重置为 Imageview,你应该使用img1.setImageResource

    btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                   //use anyone as your requirement
                    img1.setBackgroundResource(); // for set background resource from drawable folder(for src)
                    img1.setBackground();// for set background(Drawable)(for background)
                    img1.setBackgroundColor(); //for set background color(for background)
                    
                }
            });

我不确定我是否正确理解了这个问题,但如果你的意思是用按钮上的 onClick 事件更改特定图像背景..如果你有图像参考更改它..但如果你的意思是你正在像内部一样动态添加图像视图for 循环,您没有参考,您可以创建 Arraylist 并将添加的图像添加到其中,然后循环此 arraylist 以更改所有图像背景或过滤您要更改的特定图像

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM