RecycleView - 使用ConstraintLayout item布局错乱,使用inflate填充View

本文介绍了在RecycleView中,使用ConstraintLayout作为item布局时可能出现的显示问题。当通过onCreateViewHolder回调创建View对象,由于LayoutParams为空,导致布局大小不正确。解决方案包括手动设置LayoutParams或使用LayoutInflater.inflate()方法,但需传入父控件并确保attachToRoot参数为false,以避免布局混乱。
摘要由CSDN通过智能技术生成

在Recycleview中,通过 onCreateViewHolder 回调函数中创建 item 的view对象,如果创建方式为:

View view = View.inflate(context, layoutId, null); 

或者

LayoutInflater factory = LayoutInflater.from(context);
View view = factory.inflate(layoutId, null);

这里需要注意,获取的 View 对象,其LayoutParams为空,如果直接使用会发现布局出现大小不对的情况。
解决方案为手动创建LayoutParams对象并赋值给View对象。

View view = View.inflate(context, layoutId, null);
RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.MATCH_PARENT);
view.setLayoutParams(layoutParams);

或者通过如下方式创建View对象,但是需要传递View的父控件对象,并且
attachToRoot参数要设置为false

LayoutInflater factory = LayoutInflater.from(parent.getContext());
View view = factory.inflate(layoutId, parent, false);

方法原型如下:

 public
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值