如何缩小RecyclerView条目间距?实现横向分页显示部分下一条目
实现横向RecyclerView居中显示+部分相邻条目可见效果
嘿,我来帮你搞定这个需求!要让横向RecyclerView在居中显示当前条目的同时,还能露出部分下一条目,咱们只需要调整几个关键地方就行,下面一步步来:
1. 调整RecyclerView的内边距与裁剪设置
首先在你的recyclerInit()方法里,给RecyclerView添加左右内边距,并关闭内容裁剪,这样条目可以延伸到内边距区域,露出部分相邻条目:
fun recyclerInit() { val list : ArrayList<String> = ArrayList() for (i in 1..10) { list.add("$i") } recyclerview.apply { layoutManager = LinearLayoutManager(this@MainActivity, LinearLayoutManager.HORIZONTAL, false) setHasFixedSize(true) adapter = RecyclerAdapter(list) // 设置左右内边距,数值根据你想要露出的宽度调整,这里用dp转px的方式更适配 val padding = resources.getDimensionPixelSize(R.dimen.recycler_side_padding) setPadding(padding, 0, padding, 0) // 关闭裁剪,让条目可以显示在padding区域 clipToPadding = false } val snapHelper = PagerSnapHelper() snapHelper.attachToRecyclerView(recyclerview) }
别忘了在res/values/dimens.xml里添加这个内边距的定义:
<dimen name="recycler_side_padding">40dp</dimen>
2. 修改Item布局,让条目宽度小于屏幕宽度
接下来调整你的Item布局(box_elem.xml),让每个条目的宽度小于屏幕宽度,这样才能在居中时露出旁边的条目。这里用百分比宽度来适配不同屏幕:
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:id="@+id/box_elem" android:layout_width="0dp" android:layout_height="wrap_content" android:src="@drawable/original_box" <!-- 设置条目宽度为屏幕的80%,你可以根据需求调整这个数值 --> app:layout_constraintWidth_percent="0.8" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent"/> </android.support.constraint.ConstraintLayout>
3. 确认主布局包含RecyclerView
哦对了,确保你的activity_main.xml里正确引用了RecyclerView控件(你之前的代码里没贴这部分,这里补个示例):
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerview" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"/> </android.support.constraint.ConstraintLayout>
效果说明
这样修改之后,你的横向RecyclerView会:
- 保持
PagerSnapHelper的居中分页效果,滚动后条目自动居中 - 当前条目居中显示时,左右会露出部分相邻的条目(宽度由你设置的内边距和条目百分比宽度决定)
- 滚动过程中也能看到相邻条目的完整过渡
内容的提问来源于stack exchange,提问作者Manu13k
相关产品推荐
相关产品推荐

