指定的子项已经有父项,您必须调用removeview

时间:2013-11-15 12:01:46

标签: android

我删除了所有视图,然后添加了一个视图,但仍然收到此错误。

btn2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {


                if(isHierarchical){

                    IndexTableActivity.this.setContentView(R.layout.activity_main);
                    final ExpandableListView expListView = (ExpandableListView) findViewById(R.id.laptop_list);

                    booksLV = (ListView)findViewById(R.id.booksLV);
                    System.out.println("THE NUMBERRRRRRRRRRRRRRRRRRRR "+expListView);
                    btn2.setText("L");
                    isHierarchical=false;
                        createGroupList();
                        createCollection();


                        final ExpandableListAdapter expListAdapter = new ExpandableListAdapter(
                                IndexTableActivity.this, groupList, laptopCollection);

                        IndexTableActivity.this. setContentView(R.layout.main);

                        LinearLayout listView = (LinearLayout) findViewById(R.id.listView);
                        ViewGroup parentViewGroup = (ViewGroup) listView.getParent();
                        if (parentViewGroup != null) {
                            parentViewGroup.removeAllViewsInLayout();;
                            parentViewGroup.removeAllViews();

                        }
                        listView.removeAllViews();

                        listView.addView(expListView);// am getting error here 
                        expListView.setAdapter(expListAdapter);
                }else{
                    btn2.setText("H");

                    isHierarchical=true;
                }
            }
        });

请帮我找出导致此错误的原因?以及如何解决它。

错误日志

enter image description here 谢谢

1 个答案:

答案 0 :(得分:0)

从你的代码中,它有点复杂,无法理解你想要实现的目标。因为首先要添加布局,然后直接删除它,然后再将视图添加到已删除的布局中。真奇怪。

删除listView.removeAllViews();,因为您已经删除了视图,然后尝试将另一个视图添加到其中。这是错误的方式。

删除以下代码:

         if (parentViewGroup != null) {
                        parentViewGroup.removeAllViewsInLayout();;
                        parentViewGroup.removeAllViews();

                    }
      listView.removeAllViews();

首先将视图添加到布局中。

     listView.addView(expListView);// am getting error here 
     expListView.setAdapter(expListAdapter);