问题描述
我需要在recyclerview中检测滚动的开始/结束和方向.滚动侦听器有两种方法:onScrolled()
和onScrollStateChanged()
.在滚动开始后调用第一个方法(实际上称为onScrolled()而不是onScrolling()).第二种方法提供有关状态的信息,但是我没有方向信息.我如何实现我的目标?
I need to detect the start/end and direction of scroll in a recyclerview. The scroll listener has two methods: onScrolled()
and onScrollStateChanged()
. The first method is called after the scroll is started (indeed is called onScrolled() and not onScrolling()). The second method gives information about the state but I don't have the direction information. How can I achieve my goal?
推荐答案
步骤1您可以创建一个扩展RecyclerView.OnScrollListener的类并覆盖这些方法
step 1 You can create a class extending RecyclerView.OnScrollListener and override these methods
public class CustomScrollListener extends RecyclerView.OnScrollListener {
public CustomScrollListener() {
}
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
switch (newState) {
case RecyclerView.SCROLL_STATE_IDLE:
System.out.println("The RecyclerView is not scrolling");
break;
case RecyclerView.SCROLL_STATE_DRAGGING:
System.out.println("Scrolling now");
break;
case RecyclerView.SCROLL_STATE_SETTLING:
System.out.println("Scroll Settling");
break;
}
}
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (dx > 0) {
System.out.println("Scrolled Right");
} else if (dx < 0) {
System.out.println("Scrolled Left");
} else {
System.out.println("No Horizontal Scrolled");
}
if (dy > 0) {
System.out.println("Scrolled Downwards");
} else if (dy < 0) {
System.out.println("Scrolled Upwards");
} else {
System.out.println("No Vertical Scrolled");
}
}
}
第2步,因为不赞成使用setOnScrollListener,所以最好使用addOnScrollListener
step 2- Since setOnScrollListener is deprecated It is better to use addOnScrollListener
mRecyclerView.addOnScrollListener(new CustomScrollListener());
这篇关于在recyclerview中检测开始滚动和结束滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!