Horizo​​ntalScrollView中的removeAllViews不会删除视图

时间:2015-06-05 22:35:20

标签: android baseadapter horizontalscrollview

由于这段代码,我很少崩溃:(我的设备上没有崩溃) 崩溃是:java.lang.IllegalStateException:指定的子节点已经有父节点。您必须首先在孩子的父母上调用removeView()

这是代码(我添加了一个try和catch来确保这是导致问题的代码):

 @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    ...
        LinearLayout newView = getItem(position).getNewView();
        HorizontalScrollView hv = (HorizontalScrollView)view.findViewById(R.id.s_scrollview);
        hv.removeAllViews();
        if(newView != null){
            try {
                hv.addView(newView);
            }catch(Exception e){
                e.printStackTrace(); 
// I also send a remote crash log here that is how I confirmed that the crash it is here. I never get a crash on my devices
            }
        }
    ...
    }

这非常令人沮丧。有谁知道出了什么问题? 谢谢!

1 个答案:

答案 0 :(得分:1)

问题是newView已经有了父级。例外情况表明,父母应首先删除其子女。那看起来像那样:

if(newView != null){
    ((ViewGroup)view.getParent()).removeView(newView);
    hv.addView(newView);
}