实现RecyclerView、listView、gridview和ScrollView监听滑到底部的功能
1、监听RecyclerView滑到底部只要实现这个方法addOnScrollListener()
RecyclerView collectRecycle;
collectRecycle.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//当前RecyclerView显示出来的最后一个的item的position
int lastPosition = -1;
//当前状态为停止滑动状态SCROLL_STATE_IDLE时
if(newState == RecyclerView.SCROLL_STATE_IDLE){
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
if(layoutManager instanceof GridLayoutManager){
//通过LayoutManager找到当前显示的最后的item的position
lastPosition = ((GridLayoutManager) layoutManager).findLastVisibleItemPosition();
}else if(layoutManager instanceof LinearLayoutManager){
lastPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
}else if(layoutManager instanceof StaggeredGridLayoutManager){
//因为StaggeredGridLayoutManager的特殊性可能导致最后显示的item存在多个,所以这里取到的是一个数组
//得到这个数组后再取到数组中position值最大的那个就是最后显示的position值了
int[] lastPositions = new int[((StaggeredGridLayoutManager) layoutManager).getSpanCount()];
((StaggeredGridLayoutManager) layoutManager).findLastVisibleItemPositions(lastPositions);
lastPosition = findMax(lastPositions);
}
//时判断界面显示的最后item的position是否等于itemCount总数-1也就是最后一个item的position
//如果相等则说明已经滑动到最后了
if(lastPosition == recyclerView.getLayoutManager().getItemCount()-1){
// Toast.makeText(getContext(), "滑动到底了", Toast.LENGTH_SHORT).show();
LogHelper.d(TAG,"------滑动到底了---");
if (storeCollectLists.size()<count) {
//滑到底部的处理 DO
}
}
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
}
});
//找到数组中的最大值
private int findMax(int[] lastPositions) {
int max = lastPositions[0];
for (int value : lastPositions) {
if (value > max) {
max = value;
}
}
return max;
}
2、监听ListView,gridview滑到底部只要实现这个方法setOnScrollListener()
listview.setOnScrollListener(new OnScrollListener(){
@Override
public void onScrollStateChanged(AbsListView view, int scrollState){
// 当不滚动时
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
// 判断是否滚动到底部
if (view.getLastVisiblePosition() == view.getCount() - 1) {
//加载更多功能的代码
}
}
}
});
3、ScrollView滑到底部只要实现这个方法setOnScrollToBottomLintener()方法就行
mainScroll.setOnScrollToBottomLintener(new MyScrollView01.OnScrollToBottomListener() {
@Override
public void onScrollBottomListener(boolean isBottom) {
if (isBottom){
LogHelper.d(TAG,"----isBottom----"+isBottom);
//底部加载更多数据
}else{
//ToastUitl.showLong("数据加载完了");
}
}
}
});
当然了,在scrollview中嵌套recycleview、listview和gridview也可以
网友评论