简体   繁体   English

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

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

Add View dynamically in LinearLayout and after adding View change any View background on the click button.在 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);   

On button, click change all imageview background or particular ImageView.在按钮上,单击更改所有 imageview 背景或特定 ImageView。

Note: llLayout is my linear layout this layout adding in XML注意: llLayout是我的线性布局这个布局在XML中加入

when you are adding imageView into linear layout, at that time you are setImageBitmap to imageView.当您将 imageView 添加到线性布局中时,此时您将setImageBitmap设置为 imageView。

if you want to reset Image to Imageview, you should use img1.setImageResource如果你想将图像重置为 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)
                    
                }
            });

I am not sure if I understand the question correctly, but If you mean change specific image background with onClick event on a button.. If you have the image reference change it.. but if you mean you are adding the image view dynamically like inside for loop and you don't have the reference you can create Arraylist and add the added images into it then loop on this arraylist to change all the images background or filter the specific image you want to change我不确定我是否正确理解了这个问题,但如果你的意思是用按钮上的 onClick 事件更改特定图像背景..如果你有图像参考更改它..但如果你的意思是你正在像内部一样动态添加图像视图for 循环,您没有参考,您可以创建 Arraylist 并将添加的图像添加到其中,然后循环此 arraylist 以更改所有图像背景或过滤您要更改的特定图像

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

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