正在将一个ViewGroup的内容复制到另一个



嗨,我需要通过复制和粘贴ViewGroup来获得ViewGroup的副本,但位置不完全相同。所以我试着这样做,结果是:

public void ViewGroupCopy(ViewGroup source,int sourceOffset,ViewGroup destination,int destinationOffset){
    for(int i=sourceOffset;i<source.getChildCount();i++){
        View view = source.getChildAt(i);
        source.removeView(view);
        destination.addView(view, destinationOffset+i, view.getLayoutParams());
    }

我在这段代码中使用了方法:

            Activity host = (Activity) this.getContext();
            View contentView = host.findViewById(android.R.id.content).getRootView();
    ViewGroup children = (ViewGroup) contentView;
    ViewGroup oldChildren = (ViewGroup) contentView;
    children.removeAllViews();
    children.addView(new Preview(context));
    ViewGroupCopy(oldChildren,0,children,1);

为了获得更多信息,此类扩展了一个视图。

当我尝试使用这个时,我会在我的LogCat中得到这个。

09-08 16:34:30.12:E/AndroidRuntime(10992):java.lang.RuntimeException:无法启动活动ComponentInfo{com.example.worknwalk/com.example.wworknwalk.Text}:java.lang.IndexOutOfBoundsException:index=1计数=0

有人能帮帮我吗?谢谢

尝试使用相同的索引从源组获取视图。每次从源中删除视图时,都会在该索引处获得一个新视图。此外,当sourceOffset>0时,destinationOffset+i可能存在错误。这里可能没有错误,但我不完全确定例如,当您将索引为10的项目添加到包含6个项目的列表中时的行为。它可能会崩溃,也可能不会崩溃。无论如何,试试这个:

public void ViewGroupCopy(ViewGroup source, int sourceOffset,
        ViewGroup destination, int destinationOffset) {
    int limit = source.getChildCount() - sourceOffset;
    for (int i = 0; i < limit; i++) {
        View view = source.getChildAt(sourceOffset);
        source.removeView(view);
        destination.addView(view, destinationOffset + i,
                view.getLayoutParams());
    }
}

最新更新