Search code examples
javaandroidviewimageview

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.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.

Note : llLayout is my linear layout this layout adding in XML


Solution

  • when you are adding imageView into linear layout, at that time you are setImageBitmap to imageView.

    if you want to reset Image to Imageview, you should use 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)
                        
                    }
                });