How to implement endless list with RecyclerView?

前端 未结 30 2711
无人及你
无人及你 2020-11-22 02:22

I would like to change ListView to RecyclerView. I want to use the onScroll of the OnScrollListener in RecyclerView to determine if a

30条回答
  •  太阳男子
    2020-11-22 03:14

    Here is another approach. It will work with any layout manager.

    1. Make Adapter class abstract
    2. Then create an abstract method in adapter class (eg. load())
    3. In onBindViewHolder check the position if last and call load()
    4. Override the load() function while creating the adapter object in your activity or fragment.
    5. In the overided load function implement your loadmore call

    For a detail understanding I wrote a blog post and example project get it here http://sab99r.com/blog/recyclerview-endless-load-more/

    MyAdapter.java

    public abstract class MyAdapter extends RecyclerView.Adapter{
    
            @Override
            public void onBindViewHolder(ViewHolder holder, int position) {
                //check for last item
                if ((position >= getItemCount() - 1))
                    load();
            }
    
            public abstract void load();
    }
    

    MyActivity.java

    public class MainActivity extends AppCompatActivity {
        List items;
        MyAdapter adapter;
    
       @Override
        protected void onCreate(Bundle savedInstanceState) {
        ...
        adapter=new MyAdapter(items){
                @Override
                public void load() {
                    //implement your load more here
                    Item lastItem=items.get(items.size()-1);
                    loadMore();
                }
            };
       }
    }
    

提交回复
热议问题