android-recyclerview - RecyclerView show many items and make current item in center
问题描述
Like this.
- Show three items at screen, but left and right item show only edge
- When index = 0, show first item at center
- When index = n, show current item at center
|-----------------------------------| | | | | | |---------------| |----| | | | | | | | | | | | | | | | | | | | | | | 1 | | 2 | | | | | | | | | | | | | | | | | | | | | | |---------------| |----| | | | | |-----------------------------------| |-----------------------------------| | | | | |----| |---------------| |----| | | | | | | | | | | | | | | | | | | | | | | | | | 1 | | 2 | | 3 | | | | | | | | | | | | | | | | | | | | | | | | | |----| |---------------| |----| | | | | |-----------------------------------|
I have try SnapHelper, but I don't known how
解决方案
为了使第一个和最后一个项目居中,您需要在 RecyclerView 的开头和结尾创建额外的空间。一个简单的方法是使用 ItemDecoration,如下所示:
class BoundsOffsetDecoration : ItemDecoration() {
override fun getItemOffsets(outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
val itemPosition = parent.getChildAdapterPosition(view)
// It is crucial to refer to layoutParams.width (view.width is 0 at this time)!
val itemWidth = view.layoutParams.width
val offset = (parent.width - itemWidth) / 2
if (itemPosition == 0) {
outRect.left = offset
} else if (itemPosition == state.itemCount - 1) {
outRect.right = offset
}
}
}
对于“中心”效果,您应该使用PagerSnapHelper
:
PagerSnapHelper().attachToRecyclerView(recyclerView)
如果您需要更多详细信息,我已经写了一篇Medium 文章,描述了使用 RecyclerView 和 SnapHelper 逐步实现这种轮播。
推荐阅读
- python - 在代码中使用并使用 Windows
- typescript - 导出你的类不像使用私有构造函数那样严格吗?
- python - Python:检查先前时间戳中是否存在唯一ID,如果存在,则检查之前的时间戳(依此类推)
- discord.py - 试图做一种 pls dep all 或 pls dep max 之类的东西
- php - 试图在 php 中检查上午 9 点以上的时间,但不会在 10 点以上做任何事情?
- javascript - 如何在承诺链中返回一个值?
- firebase - Firebase Cloud Function 中忽略的 4GB 内存分配
- sql - 在 Access VBA SQL 中更新链接表时向 Access 表添加新记录
- javascript - 在模态引导程序 4 MVC 中加载部分视图
- google-apps-script - 加快谷歌应用程序脚本,以便我可以在 Shopify 5 秒限制内返回成功响应