Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android -How to load more items for recycleView on scroll

I'm using recycle view , I'm getting data from net via json and use adapter to add items to my recycle view . I want to get new items when user reaches the end of the recycle view .

I'm using GridLayoutManager for my recycle view . this is the code :

    int pastVisiblesItems, visibleItemCount, totalItemCount;
    GridLayoutManager mLayoutManager;
    private boolean loading = true;

recycle=(RecyclerView)findViewById(R.id.recycle);
        mLayoutManager = new GridLayoutManager(this, 3);
        // (Context context, int spanCount)
        recycle.setLayoutManager(mLayoutManager);

recycle.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

                visibleItemCount = mLayoutManager.getChildCount();
                totalItemCount = mLayoutManager.getItemCount();
                pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
                if (loadmore) {
                    if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                        page = page + 1;
                        Toast.makeText(Cats.this, "test", Toast.LENGTH_SHORT);
                    }
                }
            }
        });

I get to end of the recycleview but it doesn't show me any toast , so I think it doesn't understand that I reached the end of recycle view .

What is wrong with this code ?

like image 444
navidjons Avatar asked Jan 08 '23 15:01

navidjons


1 Answers

I was frustrated with this for a long time. But finally found a workaround. If you are using a RecyclerView you must have used a custom adapter too. In the place where you populate the view just check if you are populating the last element on the list.

public abstract class Adapter extends RecyclerView.Adapter<VH> {

    protected final List<String> items;
    protected final Context context;

    protected Adapter(Context context) {
        this.context = context;
        this.items = new ArrayList<>();
    }

    @SuppressWarnings("unused")
    public final void add(String item) {
        items.add(item);
        notifyDataSetChanged();
    }

    @Override
    public final void onBindViewHolder(VH holder, int position) {
        holder.textView.setText(items.get(position).toString());
        if (position == items.size() - 1) 
            // Reached End of List
    }

    @Override
    public final int getItemCount() {
        return items.size();
    }

}
like image 193
CuriousCat Avatar answered Jan 29 '23 05:01

CuriousCat