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

RecyclerView的ConstraintLayout条目设置match_parent后未占满屏幕宽度

解决方案

问题根因

问题出在RecipeListAdapter.kt的onCreateViewHolder方法中,View Binding加载条目布局时没有传入父布局参数,导致条目根布局设置的layout_width="match_parent"属性无法被正确解析,系统默认使用wrap_content作为条目宽度。

修复代码

修改onCreateViewHolder中的布局加载逻辑,传入父布局parent,并将第三个参数attachToRoot设置为false:

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecipeViewHolder {
    return RecipeViewHolder(
        RecipeListEntryBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
    )
}

原理说明

RecyclerView的条目在绑定到父布局前,需要基于父布局的LayoutParams测量自身尺寸,如果inflate时不传入parent参数,条目布局的根布局参数会完全失效,不管XML中设置的是match_parent还是固定数值,都会被替换为默认的wrap_content。修改后条目即可正确读取XML中设置的宽度属性,充满RecyclerView的可用宽度。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 05:45:07