Android基础:三种inflate的区别

2023-05-16

inflate的3种方式

View.inflate(…)
inflater.inflate(…)
LayoutInflater.from(getActivity()).inflate(…)

实例: 类:MenuFragment

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
       view = inflater.inflate(R.layout.layout_menu, null);//正确

//      view = inflater.inflate(R.layout.layout_menu, container, false);//正确
//      view = View.inflate(getActivity(), R.layout.layout_menu, null);//正确
//      view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_menu, null);//正确,跟参数LayoutInflater inflater一样


//      view = inflater.inflate(R.layout.layout_menu, container);//错误
//      view = inflater.inflate(R.layout.layout_menu, container, true);//错误
//      view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_menu, container);//错误

        return view;
}

错误:

Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child’s parent first.

截图:

原因:

创建fragment的时候,会自动给view添加parent,如果我们还用container的话,就会有2个parent,所以报错,所以我们就不需要用container。

解决方法:

不用container,直接填null。
如若用container的话,那么第三个参数必须是false,表示该view不与此parent绑定。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android基础:三种inflate的区别 的相关文章

随机推荐