当前位置: 代码迷 >> Android >> The specified child already has a parent. You must call removeView() on the chil,该如何解决
  详细解决方案

The specified child already has a parent. You must call removeView() on the chil,该如何解决

热度:140   发布时间:2016-04-28 03:03:41.0
The specified child already has a parent. You must call removeView() on the chil
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewSwitcher=new ViewSwitcher(TestApp.getContext());
viewSwitcher.setFactory(new ViewFactory(){
@Override
public View makeView() {
// TODO Auto-generated method stub
RelativeLayout rl = new RelativeLayout(TestApp.getContext());
        return rl;
}});
((RelativeLayout)viewSwitcher.getCurrentView()).setBackgroundColor(Color.RED);
((RelativeLayout)viewSwitcher.getNextView()).setBackgroundColor(Color.BLUE);


layoutMain=new RelativeLayout(TestApp.getContext());
RelativeLayout rl=((RelativeLayout)viewSwitcher.getNextView());
RelativeLayout.LayoutParams par=new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
layoutMain.setBackgroundColor(Color.GREEN);
layoutMain.addView(rl, par);
setContentView(layoutMain);
}

能否解释下为何会出现
The specified child already has a parent. You must call removeView() on the child's parent first.
我的原意是每隔一段时间去除switch中的view来添加进layoutMain
------解决思路----------------------
在添加的时候先判断之前是否有放入view。如果有那就先removeView掉,然后再addView
  相关解决方案