GitOPEN's Home.

自定义RecyclerView监听滑动到底部Bottom

Word count: 432 / Reading time: 2 min
2017/01/07 Share

前言

最近在做一个本地的万能播放器,需要监听RecyclerView滑动到底部,向用户提示已经滑动到最底部;看了网上其他童鞋的写法,比较繁琐。现在给出我的实现方法,非常简单实用,在监听回调方法中,可以做很多想做的事情:

1.提示用户已经到达底部(Snack或者Toast);
2.可以加载更多(我最讨厌格外加一个item来显示加载更多,于是当到达底部后直接给Adapter添加数据就好);
3.可以额外再添加一个控件,来实现快速返回顶部(由你自己实现);
4.等等。。。。(只要你判断好了到达底部,就可以在底部做自己想干的事情)。

预览图

自定义RecyclerView监听滑动到底部Bottom

SuperRecycler.java代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class SuperRecycler extends RecyclerView {

private OnBottomCallback mOnBottomCallback;

public interface OnBottomCallback {
void onBottom();
}

public void setOnBottomCallback(OnBottomCallback onBottomCallback) {
this.mOnBottomCallback = onBottomCallback;
}

public SuperRecycler(Context context) {
this(context, null);
}

public SuperRecycler(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}

public SuperRecycler(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

@Override
public void onScrolled(int dx, int dy) {

if (isSlideToBottom()) {
mOnBottomCallback.onBottom();
}
}

/**
* 其实就是它在起作用。
*/
public boolean isSlideToBottom() {
return this != null
&& this.computeVerticalScrollExtent() + this.computeVerticalScrollOffset()
>= this.computeVerticalScrollRange();
}

}

使用方法

1
2
3
4
5
6
7
8
9
10
SuperRecycler recycler = (SuperRecycler) mFraView.findViewById(R.id.recycler);
GridLayoutManager manager = new GridLayoutManager(getActivity(), 2, GridLayoutManager.VERTICAL, false);
recycler.setLayoutManager(manager);
recycler.setAdapter(mAdt);
recycler.setOnBottomCallback(new SuperRecycler.OnBottomCallback() {
@Override
public void onBottom() {
Snackbar.make(recycler, "滚动到了底部", Snackbar.LENGTH_SHORT).show();
}
});

结语

代码非常简单,用起来也很方便。大家有问题的话,可以看下面的联系方式找到我,我们一起讨论。



欣慰帮到你 一杯热咖啡
【奋斗的Coder!】企鹅群
【奋斗的Coder】公众号
CATALOG
  1. 1. 前言
    1. 1.1. 预览图
    2. 1.2. SuperRecycler.java代码:
    3. 1.3. 使用方法
    4. 1.4. 结语