RecyclerView中item布局的"match_parent"属性失效--LayoutInflate的深入了解

本文探讨了在使用RecyclerView时,Item布局设置为match_parent不起作用的问题。通过深入分析LayoutInflater的inflate方法源码,揭示了问题根源在于root参数设置及attachToRoot标志位的影响。

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

用recyclerview,给item布局使用了match_parent属性,运行后不起作用。查了下。是在onCreateViewHolder中加载布局时候出了问题。
一开始用的View.Inflate方法。查看源码后,发现View.inflate也是调用了LayoutInflat而的inflate方法
public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
LayoutInflater factory = LayoutInflater.from(context);
return factory.inflate(resource, root);
}

而在LayoutInflater中,最后调用的是

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
···
}

分析源码

if (root != null) {
                   if (DEBUG) {
                   System.out.println("Creating params from root: " +
                                    root);
                   }
                    // Create layout params that match root, if supplied
                   params = root.generateLayoutParams(attrs);
                   if (!attachToRoot) {
                   // Set the layout params for temp if we are not
                   // attaching. (If we are, we use addView, below)
                     temp.setLayoutParams(params);
                        }
                    }

要执行setLayoutParams方法,需要root不能为空,切attachToRoot为false。感觉有空LayoutInflater还得再看一下。这里有hongyan大神的一篇讲LayoutInflater的。感觉还是得仔细看一下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值