如何移除RecyclerView的GridLayoutManager中CardView的右侧边距

问题原因分析
- 核心原因是你的CardView使用了固定宽度
@dimen/_146sdp,两列并排总宽度为292sdp,当设备可用屏幕宽度大于该值时,剩余未占满的空间会默认留在RecyclerView右侧,形成可见边距 - 次要排查点1:你开启了
app:cardUseCompatPadding="true",该属性为了兼容低版本CardView的阴影渲染,会自动给CardView添加额外内边距,也可能放大边距视觉效果 - 次要排查点2:可检查RecyclerView的父布局是否设置了未察觉的右侧padding,可通过Android Studio的布局边界预览工具确认
解决方法
方法1:修改CardView宽度为自适应(最简单)
直接将CardView的布局宽度属性改为match_parent,GridLayoutManager会自动将每列宽度平均分配给对应item,自动占满整个RecyclerView宽度:
<com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/cardView1" android:layout_width="match_parent" <!-- 仅修改这一行即可 --> android:layout_height="@dimen/_175sdp" app:cardCornerRadius="@dimen/_20sdp" app:cardElevation="0dp" app:cardMaxElevation="0dp" app:cardPreventCornerOverlap="false" app:cardUseCompatPadding="true" app:strokeColor="@android:color/darker_gray" app:strokeWidth="@dimen/_1sdp">
方法2:动态计算item宽度适配(适合需要控制固定宽高比的场景)
在Adapter的onCreateViewHolder方法中,动态计算每个item的宽度为屏幕宽度除以列数,再设置给item布局:
@Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.你的卡片布局文件名, parent, false); // 动态设置item宽度 GridLayoutManager.LayoutParams layoutParams = (GridLayoutManager.LayoutParams) view.getLayoutParams(); int screenWidth = parent.getContext().getResources().getDisplayMetrics().widthPixels; // 如果需要设置item间间距,可以在这里减去总间距后再除以列数 layoutParams.width = screenWidth / 2; view.setLayoutParams(layoutParams); return new MyViewHolder(view); }
可选优化:关闭兼容内边距
如果不需要兼容Android 5.0以下系统,可将app:cardUseCompatPadding改为false,消除CardView自带的额外内边距:
app:cardUseCompatPadding="false"
内容的提问来源于stack exchange,提问作者mayra
相关产品推荐
相关产品推荐

