水平居中 RecyclerView 的第一项 [英] Horizontally center first item of RecyclerView

查看:40
本文介绍了水平居中 RecyclerView 的第一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 RecyclerView 来模拟 MultiViewPager 的行为,特别是我想让所选项目位于屏幕中央,包括第一个和最后一个元素.

I want to use a RecyclerView to emulate the behavior of a MultiViewPager, in particular I'd like to have the selected item at the center of the screen, including the first and the last element.

正如您在此图像中看到的,第一项居中,这将是我的预期结果.

As you can see in this image, the first item is centered and this would be my expected result.

我所做的是设置一个带有水平 LinearLayoutManagerLinearSnapHelperRecyclerView.这个解决方案的问题是第一个和最后一个项目永远不会作为选择水平居中.我应该切换我的代码以便它使用 MultiViewPager 还是可以利用 RecyclerView 获得类似的结果?

What I did was to setup a RecyclerView with an horizontal LinearLayoutManager and a LinearSnapHelper. The problem with this solution is that the first and the last item will never be horizontally centered as selection. Should I switch my code so that it uses a MultiViewPager or is it possible to achieve a similar result taking advantage of a RecyclerView?

推荐答案

您可以使用 getItemOffsets(),适当地偏移第一项和最后一项.

You can implement this with an RecyclerView.ItemDecoration in getItemOffsets(), to offset the first and last item appropriately.

检索给定项目的任何偏移量.outRect 的每个字段指定项目视图应该插入的像素数,类似于填充或边距.默认实现将 outRect 的边界设置为 0 并返回.

Retrieve any offsets for the given item. Each field of outRect specifies the number of pixels that the item view should be inset by, similar to padding or margin. The default implementation sets the bounds of outRect to 0 and returns.

如果需要访问Adapter获取额外数据,可以调用getChildAdapterPosition(View) 获取View的适配器位置.

If you need to access Adapter for additional data, you can call getChildAdapterPosition(View) to get the adapter position of the View.

您可能还需要使用物品的尺寸和RecyclerView.但是这些信息无论如何都可以使用.

You might need to use the messured size of the item and the RecyclerView as well. But these information is available to be used anyhow.

这篇关于水平居中 RecyclerView 的第一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆