我正在使用无限滚动的 recyclerview 来重复 X 个项目。 我还想使用 PagerSnapHelper() 来像 viewpager 一样捕捉滚动。
一旦我开始向左或向右滚动,PageSnapHelper()就会开始工作,就像viewpager一样,中心对齐如下 -
我想在最初加载时将 recyclerview 显示为第二张图像。请告诉下一步要做什么来实现这一目标。
这是代码 fragment -
linearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
this.recyclerView.setLayoutManager(linearLayoutManager);
SnapHelper snapHelper = new PagerSnapHelper();
adapterCarousel = new AdapterCarousel(mContext, glideRequestManager);
adapterCarousel.setViewType(RECYCLER_VIEW_TYPE_NORMAL);
adapterCarousel.setCarousel(carousel);
this.recyclerView.setAdapter(adapterCarousel);
snapHelper.attachToRecyclerView(recyclerView);
linearLayoutManager.scrollToPosition(Integer.MAX_VALUE / 2);
最佳答案
我通过使用LinearLayoutManager#scrollToPositionWithOffset(pos, offset)
解决了这个问题。我只是将滚动位置偏移了项目之间填充的一半。这对我有用,因为我的元素与屏幕宽度相同。在你的情况下,你需要做一些数学计算。
假设您的项目的宽度为 W
,您的 RecyclerView 的宽度为 rvW
,项目之间的填充为 padding
那么您想要的数量偏移量由 (rvW - W)/2 - padding/2
或 (rvW - W - padding)/2
给出。
最终代码:
// post to give the recyclerview time to layout so it's width isn't 0
mRecyclerView.post(new Runnable() {
void run() {
int padding = getResources().getDimensionPixelSize(R.dimen.some_padding);
int rvWidth = mRecyclerView.getWidth();
int itemWidth = getResources().getDimensionPixelSize(R.dimen.itemWidth);
int offset = (rvWidth - itemWidth - padding) / 2;
mLinearLayoutManager.scrollToPositionWithOffset(pos, offset);
}
});
对代码的一些可选改进:
您可以使用
View#measure()
和View#getMeasuredWidth()
甚至显示器的宽度(如果您确定),而不是发布到 RecyclerView RecyclerView 将始终适合屏幕宽度。如果您的 RecyclerView 的子级大小可变,您可以通过
mLinearLayoutManager.findViewByPosition(mLinearLayoutManager.findFirstVisibleItemPosition())
获取 View,并以这种方式获取其宽度。
关于android - 加载时将 Recyclerview 项目对齐到中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43091750/