Android开发中如何设置RecyclerView单个item的统一固定高度
问题原因
你当前代码存在几个直接导致item高度无法统一的问题:
- RecyclerView的父布局是LinearLayout,你设置的
app:layout_constraintDimensionRatio是ConstraintLayout专属属性,在这里完全不生效 android:adjustViewBounds仅对ImageView生效,对RecyclerView无任何作用- 你重写的
checkLayoutParams方法没有实际写入尺寸设置逻辑,且该方法不是强制修改item尺寸的正确位置 - RecyclerView放在普通ScrollView中存在嵌套测量冲突,设置wrap_content高度时GridLayoutManager无法按列均分尺寸
- 视频播放控件未做尺寸约束,加载视频时会按照原始视频宽高自适应撑开布局
修复步骤
1. 修正页面布局
将普通ScrollView替换为NestedScrollView,删除RecyclerView上的无效属性,修正宽度配置:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".Fragment.ProfileFragment"> <androidx.core.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/bar"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recycler_view" android:background="#ECEFF1" android:layout_width="match_parent" android:layout_height="wrap_content" android:nestedScrollingEnabled="false" android:layout_marginTop="20dp" android:layout_marginRight="3dp"/> </LinearLayout> </androidx.core.widget.NestedScrollView> </RelativeLayout>
嵌套滚动场景下必须给RecyclerView设置
android:nestedScrollingEnabled="false",避免测量冲突。
2. 动态计算并固定item尺寸
删除你之前重写的无效checkLayoutParams代码,在RecyclerView Adapter的onCreateViewHolder方法中,动态计算每个item的宽高并强制设置:
@NonNull @Override public MyFotoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.your_video_item_layout, parent, false); // 计算单item宽度:屏幕宽度减去右侧边距后平分为3列 Resources res = parent.getContext().getResources(); int screenWidth = res.getDisplayMetrics().widthPixels; int rightMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, res.getDisplayMetrics()); int itemWidth = (screenWidth - rightMargin) / 3; // 这里设置高度等于宽度实现正方形item,需要其他比例直接修改计算逻辑即可,比如16:9就用 itemWidth * 16 /9 int itemHeight = itemWidth; // 给item根布局设置固定宽高 ViewGroup.LayoutParams lp = itemView.getLayoutParams(); lp.width = itemWidth; lp.height = itemHeight; itemView.setLayoutParams(lp); return new MyFotoViewHolder(itemView); }
3. 配置视频控件缩放模式
在你的视频item布局中,将视频播放控件(ExoPlayer的PlayerView/TextureView等)的宽高设置为match_parent,同时配置缩放模式为裁剪填充:
- 如果用ExoPlayer PlayerView,添加属性
app:resize_mode="zoom"(即centerCrop模式) - 如果用原生TextureView,设置
android:scaleType="centerCrop"
该配置会让视频自动裁剪适配固定尺寸的item,不会按照原始视频比例撑开布局。
性能优化建议
如果页面不需要头部其他内容和列表联动滚动,直接删除NestedScrollView,将RecyclerView高度设置为match_parent,开启RecyclerView自身嵌套滚动,可大幅提升列表滑动流畅度。
内容的提问来源于stack exchange,提问作者His R.H
相关产品推荐
相关产品推荐

