首先,您试图再次添加同一个对象,这并没有什么意义 - 新视图必须是单独的对象,您必须首先复制原始对象,例如,采用.clone()方法。
但是,不幸的是,即使你做了,也不能将克隆的视图添加到ViewGroup,这是为什么。
你唯一的例外是ViewGroupchecking your View's parent for null 结果所以,为了增加克隆的观点,你必须到您的视图的mParent成员设置null,你不能这样做,因为直接,做的方法这是不公开的:View.assignParent()
你可以尝试克隆View你叫.removeViewAt()后,使其不会在克隆的时候有父母,然后加上原来的视图回到它的位置,然后用加继续克隆到需要的地方,但作为SD提到你必须克隆一些麻烦加上这种方式是非常模糊的,将需要ViewGroup重新布局2次。
更好的解决方案是为每个包含必要信息的视图分配一个标记,以创建另一个视图,并在需要克隆时使用它。
我会做这样的事情:
public interface ViewCloner {
public View clone(Context context);
}
public static class ImageViewCloner implements ViewCloner {
private int mImgResId;
public ImageViewCloner(int imgResourceId) {
this.mImgResId = imgResourceId;
}
@override
public View clone(Context context) {
ImageView view = new ImageView(context);
view.setImageBitmap(BitmapFactory.decodeResource(context.getResources(), mImgResId));
// Add the tag to the clone as well, so it, too, can be cloned
view.setTag(new ImageViewCloner(mImgResId));
return view;
}
}
// When creating the original view
int resId = R.drawable.ic_launcher;
ImageView view = new ImageView(context);
view.setImageBitmap(BitmapFactory.decodeResource(getResources(), resId));
view.setTag(new ImageViewCloner(resId));
// When cloning the view
ViewCloner vc = (ViewCloner) getChildAt(index).getTag();
View clone = vc.clone(getContext());
addView(clone);
对于任何额外的视图或组你要改为使用的单ImageView的事情就是创建一个ViewCloner另一种实现方式,你是好去无必须修改你的容器的行为。