fragment第二次载入就报错

来源:互联网 发布:潍坊行知学校 宿舍 编辑:程序博客网 时间:2024/06/09 14:27

fragment第二次载入就报错

1、布局中加入一个<fragment 标签,第一次载入的时候是正常的,第二次加载的时候,就直接crashed,退出

2、查到原因Caused by: java.lang.IllegalArgumentException: Binary XML file line #8: Duplicate id 0x7f0e0096, tag null, or parent id 0xffffffff with another fragment for com.xiao88.app.fragment.TestFragment

3、这个是XML布局加载的时候报的错,重复了,而且是发生在fragment标签上的

4、解决方法:

重载方法,实现自动清除,这样就不会重复了。

@Override
public void onDestroyView() {
super.onDestroyView();
TestFragment testFragment = (TestFragment) getFragmentManager().findFragmentById(R.id.test);
if (testFragment != null) {
getFragmentManager().beginTransaction().remove(testFragment).commit();
}
}

he answer Matt suggests works, but it cause the map to be recreated and redrawn, which isn't always desirable. After lots of trial and error, I found a solution that works for me:

private static View view;@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {    if (view != null) {        ViewGroup parent = (ViewGroup) view.getParent();        if (parent != null)            parent.removeView(view);    }    try {        view = inflater.inflate(R.layout.map, container, false);    } catch (InflateException e) {        /* map is already there, just return view as it is */    }    return view;}

1 0
原创粉丝点击