Android关于inflate的root参数

本文详细解析了View inflate方法的使用技巧,特别是在第三个参数ViewGroup不为空的情况下的注意事项。通过具体的例子说明了如何正确使用此方法避免错误。

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

最近在用View inflate(Context context, int resource, ViewGroup root)方法时,在第三个参数root上碰到了点麻烦。

一般在写ListView的adapter时,会这样加载自定义列

View imageLayout = inflate(getContext(),R.layout.item_album_pager, null);
...
viewGroup.addView(imageLayout);

如果这样写,调用imageLayout时就可能出问题

//在inflate时就把layout加入viewGroup
View imageLayout = inflate(getContext(),R.layout.item_album_pager, viewGroup);

这是由于,inflate方法在第三个参数root不为空时,返回的View就是root,而当root为空时,返回的才是加载的layout的根节点。看api解释:

Inflate a new view hierarchy from the specified xml resource. Throws InflateException if there is an error.

Parameters:
resource ID for an XML layout resource to load (e.g., R.layout.main_page)
root Optional view to be the parent of the generated hierarchy.
Returns:
The root View of the inflated hierarchy. If root was supplied, this is the root View; otherwise it is the root of the inflated XML file.

本人便是在ViewPager的adapter中,使用了root不为空的inflate方法,在返回layout时出错了。

@Override
        public Object instantiateItem(ViewGroup viewGroup, int position) {

            View imageLayout = inflate(getContext(),R.layout.item_album_pager, viewGroup);
                        ....
            //这里实际上把整个viewGroup返回了,导致出错
            return imageLayout;
        }

 

这里举例的是View类自带的inflate方法,它本质调用的就是LayoutInflater类的 View inflate(int resource, ViewGroup root)方法。

public static View inflate(Context context, int resource, ViewGroup root) {
        LayoutInflater factory = LayoutInflater.from(context);
        return factory.inflate(resource, root);
    }

 

转载于:https://www.cnblogs.com/linjzong/p/4240841.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值