Android RecyclerView item match_parent宽度不生效 预览与模拟器显示不一致
问题原因
问题出在RecyclerAdapter.kt的onCreateViewHolder方法的布局加载逻辑:
你当前使用的RecyclerItemBinding.inflate(LayoutInflater.from(parent.context))是双参数的inflate方法,没有传入父布局parent,也没有设置attachToRoot参数。这种场景下,item根布局中所有以layout_开头的配置参数都会失效,系统会默认使用wrap_content替代,所以你设置的android:layout_width="match_parent"不会生效。
修复方案
修改onCreateViewHolder中的inflate代码,传入父布局parent,同时将attachToRoot设置为false即可:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder { val binding = RecyclerItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return RecyclerViewHolder(binding) }
参数说明:
- 第二个参数
parent:RecyclerView本身会作为item的父布局,传入后系统会基于父布局计算item的layout_配置,让你写的match_parent生效 - 第三个参数
attachToRoot:设置为false是因为item的挂载逻辑由RecyclerView负责,不需要我们手动把item添加到父布局中,设为true会触发重复添加的报错。
预览与运行效果不一致的原因
布局预览工具渲染单个item布局时,会默认给item提供一个模拟的父布局容器,所以你写的match_parent可以正常生效;但运行时布局加载没有传入父布局,导致布局参数失效,因此两者表现不一致。
内容的提问来源于stack exchange,提问作者samedhrmn
相关产品推荐
相关产品推荐

