第一步:封装好一个找到Recycler的工具类起名为FindLastItem
public class FindLastItem {//无论是什么的Manager都可以进行这个类来判断,并且成功了就发送一条广播 private RecyclerView recyclerView; private Context context; public FindLastItem(RecyclerView recyclerView, Context context) { this.recyclerView = recyclerView; this.context = context; } public void refresh() { recyclerView.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) { Intent intent = new Intent("UP_DATA"); context.sendBroadcast(intent); } } } @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、然后在要用到的地方新new一个这个类 就可以,当new的时候就会调用这个工具类的构造方法,需要你往里传进去一个对象
@Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); FindLastItem findLastItem=new FindLastItem(recyclerViewDelicious,getContext()); findLastItem.refresh(); IntentFilter intentFilter =new IntentFilter("UP_DATA"); upData=new UpData(); getContext().registerReceiver(upData,intentFilter); homeKnowledgeAdapter.setOnItemClickListener(new HomeKnowledgeAdapter.OnItemClickListener() {//设置点击事件,点击进入下一个界面,并传递一个url @Override public void onItemClick(View view, int position) { Intent intent =new Intent(getContext(), MessageActivity.class); intent.putExtra("url",datas.get(position).getLink()); getContext().startActivity(intent); } }); }总的来具体说一下这个工具类
就是帮助你找到RecyclerView的最后一条,找到之后并发一个广播,一般我们都是用到更新数据用的,所以这里我就定义个广播信号UP_DATA。
当你要用的时候吧你的RecyclerView的对象传进去就好了