Android基础:三种inflate的区别

本文详细介绍了Android中inflate方法的三种使用方式,并通过具体实例解释了如何正确使用这些方法加载布局资源。此外,还探讨了常见错误及其解决办法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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绑定。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值