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

RecyclerView列表项显示异常,ImageView设置match_parent无法占满父布局问题

问题原因

列表项无法占满父布局的核心问题出在ViewHolder创建逻辑:

  • 调用ViewBinding的inflate方法时未传入父布局parent参数,导致布局文件中定义的根布局match_parent属性失效,系统会默认生成宽高为wrap_content的布局参数,最终列表项宽度无法匹配RecyclerView的宽度。
修复方案

修改FavouritesAdapter类的onCreateViewHolder方法,给inflate方法补充父布局和attachToRoot参数:

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FavouritesViewHolder {
    // 补充parent和false两个参数,false代表不手动将item挂载到parent,由RecyclerView负责处理
    return FavouritesViewHolder(MemesListItemBinding.inflate(LayoutInflater.from(parent.context), parent, false))
}
可选优化(图片显示调整)

如果需要让图片完全占满ImageView宽度且保持宽高比,可以修改列表项布局中ImageView的属性:

<ImageView
    android:id="@+id/meme_image_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    <!-- 开启自适应宽高比 -->
    android:adjustViewBounds="true"
    android:padding="8dp"
    <!-- 可选scaleType:centerCrop(裁剪超出部分占满控件)/fitCenter(完整显示图片) -->
    android:scaleType="centerCrop"
    app:imageUrl="@{memes.url}"
    tools:src="@tools:sample/backgrounds/scenic" />

内容的提问来源于stack exchange,提问作者Aman Kumar Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 02:54:06