简体   繁体   中英

ListView scroll up for refresh, scroll down to add new items to the list

Right now I have a Listview that stores 25 items, which are retrieved from an API. What I want is that the ListView refreshes on scroll up (retreive data from api call again). And add another 25 items on scroll down.

What could I use for this? I found SwipeRefreshLayout, However, I can't find a way to distinguish scroll up and scroll down.

I think your question is little bit misleading.If i am not wrong, here can be to thing.

  1. Reload List on Over Scroll Down :- This functionality can be achieve by using SwipeRefreshLayout . Follow the android tutorial for Adding Swipe-to-Refresh To Your App .

  2. Load more items on Over Scroll Up :- This is the part of Lay loading(Pagination) . If you are using ListView then you can use OnScrollListener and setFooterView() to make it done . Have a look at This thread .

Suggestion:- A simple suggestion Use RecyclerView instead of ListView to make better use of ViewHolder pattern.

Use RecyclerView instead of ListVIew . Initialize the RecyclerView as follows :

RecyclerView Initialization :

layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
videosAdapter = new VideosAdapter();
recyclerView.setItemAnimator(new SlideInUpAnimator());
recyclerView.setAdapter(videosAdapter);

// Pagination
recyclerView.addOnScrollListener(recyclerViewOnScrollListener); 

Now setup OnScrollListener :

private RecyclerView.OnScrollListener recyclerViewOnScrollListener = new 
RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
    super.onScrollStateChanged(recyclerView, newState);
}

@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
    super.onScrolled(recyclerView, dx, dy);
    int visibleItemCount = layoutManager.getChildCount();
    int totalItemCount = layoutManager.getItemCount();
    int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();

    if (!isLoading && !isLastPage) {
        if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                && firstVisibleItemPosition >= 0
                && totalItemCount >= PAGE_SIZE) {
            loadMoreItems();
        }
    }
}
};

Once you get the response you need to add the received data to the list again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM