gpt4 book ai didi

android - 在水平回收器 View 中捕捉

转载 作者:搜寻专家 更新时间:2023-11-01 08:40:33 25 4
gpt4 key购买 nike

我有一个水平的 Recycler View,我想在其中启用捕捉。我阅读了一些关于 SO 的主题并找到了 this代码工作得很好。我不太了解 Recycler View 和 Layout Managers 的内部工作原理,所以想问一下是否可以将代码修改为:

  1. 无论 throw 速度如何,我只想向前或向后移动一个项目。

  2. 捕捉速度很慢。如果我将 View 移动到宽度的一半以上,下一个项目就会进入中心但速度非常慢。可以增加它以便即时捕捉吗?

关于如何实现上述行为的任何想法都将非常有帮助。

最佳答案

在其他代码的帮助下终于弄明白了:

public class FlingRecyclerView extends RecyclerView {

int screenWidth;

public FlingRecyclerView(Context context) {
super(context);
WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
}

public FlingRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
}

public FlingRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
}

@Override
public boolean fling(int velocityX, int velocityY) {
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) getLayoutManager();

//these four variables identify the views you see on screen.
int lastVisibleView = linearLayoutManager.findLastVisibleItemPosition();
int firstVisibleView = linearLayoutManager.findFirstVisibleItemPosition();
View firstView = linearLayoutManager.findViewByPosition(firstVisibleView);
View lastView = linearLayoutManager.findViewByPosition(lastVisibleView);

//these variables get the distance you need to scroll in order to center your views.
//my views have variable sizes, so I need to calculate side margins separately.
//note the subtle difference in how right and left margins are calculated, as well as
//the resulting scroll distances.


int leftMargin = (screenWidth - lastView.getWidth()) / 2;
int rightMargin = (screenWidth - firstView.getWidth()) / 2 + firstView.getWidth();
int leftEdge = lastView.getLeft();
int rightEdge = firstView.getRight();
int scrollDistanceLeft = leftEdge - leftMargin;
int scrollDistanceRight = rightMargin - rightEdge;

//if(user swipes to the left)
if (velocityX > 0) smoothScrollBy(scrollDistanceLeft, 0);
else smoothScrollBy(-scrollDistanceRight, 0);

return true;
}
}

非常适合我的要求。希望它也能帮助其他人。

关于android - 在水平回收器 View 中捕捉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33032672/

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