10

In my android application, I want to create duplicate ImageButton of already created Imagebutton.

I want to create new Imagebutton programmatically having same widht, height, background, image src, margins etc. of already created button in XML file. In short, I want to create duplicate ImageButton.

I have try this

ImageButton mImageButton = (ImageButton) findViewById(R.id.ib);
Imagebutton duplicate = mImageButton;

But it only refer to the the mImageButton. So, change in duplicate also cause change in mImageButton.

Please help me out. Thank you...

Shaishav Jogani
  • 2,111
  • 3
  • 23
  • 33

2 Answers2

16

You cannot clone views, the way to do it is to create your View each time.

You could always inflate the view multiple times from an XML or create a function to create the view programatically.

Inflation:

private void addImageButton(ViewGroup viewGroup) {    
    View v = LayoutInflater.from(this).inflate(R.layout.ib, null);
    viewGroup.addView(v);
}

Programatically:

private void addImageButton(ViewGroup viewGroup) {    
    ImageButton imageButton = new ImageButton(context);
    viewGroup.addView(imageButton);
}
Numan1617
  • 1,158
  • 5
  • 19
  • 1
    Any difference between inflation and adding a view? – Vamsi Dec 05 '16 at 12:38
  • 5
    @Vamsi inflating a view will set its attributes to whatever you set it to be in the XML, while creating a new view programatically will set it to default values that you may not want. If you're going to be making many clones of complex views/layouts, I would recommend making an XML for it. – Max Izrin Dec 27 '16 at 12:35
  • In my case i was an edittext therefore i had to cast it to edittext. I tried the first approach , but the result was just a normal edittext without any attributes i set in the xml . Any idea why is this happening ? – Hissaan Ali Aug 25 '19 at 14:28
-1

Also be sure that you set unique id for each new clonned view. Otherwise you can get this error :

java.lang.IllegalStateException: The specified child already has a parent.

You must call removeView() on the child's parent first.

view.setId(int id);

Aditi
  • 820
  • 11
  • 27
Sadwyn
  • 1
  • 3