最近在做一个本地的万能播放器,需要监听RecyclerView滑动到底部,向用户提示已经滑动到最底部;看了网上其他童鞋的写法,比较繁琐。现在给出我的实现方法,非常简单实用,在监听回调方法中,可以做很多想做的事情:
1.提示用户已经到达底部(Snack或者Toast);
2.可以加载更多(我最讨厌格外加一个item来显示加载更多,于是当到达底部后直接给Adapter添加数据就好);
3.可以额外再添加一个控件,来实现快速返回顶部(由你自己实现);
4.等等。。。。(只要你判断好了到达底部,就可以在底部做自己想干的事情)。
public classSuperRecyclerextendsRecyclerView{
private OnBottomCallback mOnBottomCallback;
public interfaceOnBottomCallback{
voidonBottom();
}
publicvoidsetOnBottomCallback(OnBottomCallback onBottomCallback){
this.mOnBottomCallback = onBottomCallback;
}
publicSuperRecycler(Context context){
this(context, null);
}
publicSuperRecycler(Context context, @Nullable AttributeSet attrs){
this(context, attrs, 0);
}
publicSuperRecycler(Context context, @Nullable AttributeSet attrs,intdefStyle){
super(context, attrs, defStyle);
}
@Override
publicvoidonScrolled(intdx,intdy){
if (isSlideToBottom()) {
mOnBottomCallback.onBottom();
}
}
/**
* 其实就是它在起作用。
*/
publicbooleanisSlideToBottom(){
return this != null
&& this.computeVerticalScrollExtent() + this.computeVerticalScrollOffset()
>= this.computeVerticalScrollRange();
}
}
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
publicvoidonBottom(){
Snackbar.make(recycler, "滚动到了底部", Snackbar.LENGTH_SHORT).show();
}
});