You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

两个RecyclerView使用match_parent宽度布局时第二个无法匹配父容器的问题求助

问题分析与解决

你的第二个RecyclerView子项无法占满父容器宽度的核心问题,出在onCreateViewHolder的布局加载方式上!

问题根源

在你的onCreateViewHolder方法中,调用inflate时只传入了LayoutInflater,没有指定父容器(parent)和attachToRoot参数:

val binding = LicenseRecyclerviewAdapterBinding.inflate(layoutInflater)

当不传入parent时,布局文件中根视图的match_parent属性会失去参考——系统不知道它该相对于哪个父容器匹配宽度,最终导致子项宽度被内容包裹,无法占满RecyclerView的宽度。

修复方案

修改inflate方法的调用,传入parent并将attachToRoot设为false(RecyclerView会自行处理视图的附着逻辑):

override fun onCreateViewHolder(parent : ViewGroup, viewType : Int) : ViewHolder {
    val layoutInflater = LayoutInflater.from(parent.context)
    val binding = LicenseRecyclerviewAdapterBinding.inflate(layoutInflater, parent, false)
    return ViewHolder(binding)
}

额外检查项(确保万无一失)

  • 确认第二个RecyclerView(rvLicense)本身的布局宽度是match_parent,如果它的宽度不是全屏,子项自然也无法占满屏幕;
  • 你的第二个子项布局根ConstraintLayout已经设置了android:layout_width="match_parent",这部分是没问题的,不需要修改。

这个修改应该能直接解决子项宽度不匹配的问题,因为布局加载时会参考父容器(RecyclerView的ItemView)的尺寸约束,match_parent就能正常生效了。

内容的提问来源于stack exchange,提问作者lelestacia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 20:42:40