Search code examples
androidandroid-recyclerviewswiperefreshlayout

Pull up to refresh in android RecyclerView


I have used the SwipeRefreshLayout of v4 support library according to the following way:

 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            refreshItems();
        }
    });

   void refreshItems() {
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            swipeRefreshLayout.setRefreshing(false);
        }
    }, 3000);
}

In this strategy, if I pull down the screen when first list item is visible then onRefresh() method is called.

enter image description here

This is called pull down to refresh. But I want the reverse effect. That is if I pull up the screen when last list item is visible then a method should be called or it should be notified anyway. Is it possible? If possible please provide me the way.


Solution

  • In your Adapter class of RecyclerView/ListView while inflating last item you can put if statement and call a method.

    Code if you are using RecyclerView:-

    private boolean loading = true;
    int pastVisiblesItems, visibleItemCount, totalItemCount;
    
    mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() 
    {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) 
        {
            if(dy > 0) //check for scroll down
            {
                visibleItemCount = mLayoutManager.getChildCount();
                totalItemCount = mLayoutManager.getItemCount();
                pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
    
                if (loading) 
                {
                    if ( (visibleItemCount + pastVisiblesItems) >= totalItemCount) 
                    {
                        loading = false;
                        Log.v("...", "Last Item Wow !");
                        //Do pagination.. i.e. fetch new data
                    }
                }
            }
        }
    });
    

    Also add below code:-

    LinearLayoutManager mLayoutManager;
    mLayoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(mLayoutManager);