How to create Clone-Duplicate View?

做~自己de王妃 提交于 2019-12-21 04:36:13

问题


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


回答1:


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);
}



回答2:


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);



来源:https://stackoverflow.com/questions/29744039/how-to-create-clone-duplicate-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!