gpt4 book ai didi

android - RecyclerView 水平滚动对齐在中心

转载 作者:IT老高 更新时间:2023-10-28 13:13:44 35 4
gpt4 key购买 nike

我正在尝试使用 RecyclerView 在此处制作类似轮播的 View ,我希望该项目在滚动时捕捉到屏幕中间,一次一个项目。我试过使用 recyclerView.setScrollingTouchSlop(RecyclerView.TOUCH_SLOP_PAGING);

但 View 仍在平滑滚动,我也尝试使用滚动监听器实现自己的逻辑,如下所示:

recyclerView.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
Log.v("Offset ", recyclerView.getWidth() + "");
if (newState == 0) {
try {
recyclerView.smoothScrollToPosition(layoutManager.findLastVisibleItemPosition());
recyclerView.scrollBy(20,0);
if (layoutManager.findLastVisibleItemPosition() >= recyclerView.getAdapter().getItemCount() - 1) {
Beam refresh = new Beam();
refresh.execute(createUrl());
}
} catch (Exception e) {
e.printStackTrace();
}
}

现在从右向左滑动可以正常工作,但反过来不行,我在这里缺少什么?

最佳答案

LinearSnapHelper ,现在这很容易。

您需要做的就是:

SnapHelper helper = new LinearSnapHelper();
helper.attachToRecyclerView(recyclerView);

更新

自 25.1.0 起可用,PagerSnapHelper可以帮助实现类似ViewPager的效果。像使用 LinearSnapHelper 一样使用它。

旧的解决方法:

如果您希望它的行为类似于 ViewPager,请尝试以下操作:

LinearSnapHelper snapHelper = new LinearSnapHelper() {
@Override
public int findTargetSnapPosition(RecyclerView.LayoutManager layoutManager, int velocityX, int velocityY) {
View centerView = findSnapView(layoutManager);
if (centerView == null)
return RecyclerView.NO_POSITION;

int position = layoutManager.getPosition(centerView);
int targetPosition = -1;
if (layoutManager.canScrollHorizontally()) {
if (velocityX < 0) {
targetPosition = position - 1;
} else {
targetPosition = position + 1;
}
}

if (layoutManager.canScrollVertically()) {
if (velocityY < 0) {
targetPosition = position - 1;
} else {
targetPosition = position + 1;
}
}

final int firstItem = 0;
final int lastItem = layoutManager.getItemCount() - 1;
targetPosition = Math.min(lastItem, Math.max(targetPosition, firstItem));
return targetPosition;
}
};
snapHelper.attachToRecyclerView(recyclerView);

上面的实现只是根据速度的方向返回当前项目旁边的位置(居中),而不考虑大小。

前一个是包含在支持库版本 24.2.0 中的第一方解决方案。这意味着您必须将其添加到您的应用模块的 build.gradle 或更新它。

compile "com.android.support:recyclerview-v7:24.2.0"

关于android - RecyclerView 水平滚动对齐在中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29134094/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com