Android基础:三种inflate的区别

来源:互联网 发布:socket多线程编程 编辑:程序博客网 时间:2024/06/06 03:29

inflate的3种方式

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

实例: 类:MenuFragment

@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,        Bundle savedInstanceState) {       view = inflater.inflate(R.layout.layout_menu, null);//正确//      view = inflater.inflate(R.layout.layout_menu, container);//错误//      view = inflater.inflate(R.layout.layout_menu, container, false);//正确//      view = inflater.inflate(R.layout.layout_menu, container, true);//错误//      view = View.inflate(getActivity(), R.layout.layout_menu, null);//正确    //跟参数LayoutInflater inflater一样//      view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_menu, null);//正确//      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绑定。

0 0
原创粉丝点击