david
david

Reputation: 2958

Is it possible to get an estimate of children of RecyclerView.Adapter count before adding items in android?

Is it possible to get an estimate of children of RecyclerView.Adapter count before adding items in android?

What I would want is that I want to estimate the children count of an Adapter before adding items to it so that I could estimate the visible items I could only insert.

Like for Example a Tablet

  1. A Tablet can have many children view than a Phone
  2. A Phone could have lesser children than a Tablet

Getting an estimate how many children or items (is an advantage for my case) I can add to the adapter so that it fits visibly at first population of my data to my adapter.

Upvotes: 2

Views: 788

Answers (1)

PPartisan
PPartisan

Reputation: 8231

This might work. It should return all child views of your ViewHolder that are visible. You could also try it by replacing firstItem with 0 and lastItem with recyclerView.getAdapter().getItemCount():

private static int getRecyclerViewChildCount(RecyclerView recyclerView) {

    //This below section is a bit clumsy, but the findFirstVisibleItem() etc. methods
    //Only apply to LinearLayoutManagers and their subclasses.
    try { 
        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager(); 
    } catch (ClassCastException e) {
        throw new IllegalArgumentException("LayoutManager must be of type " + LinearLayoutManager.class.getSimpleName());
    }

    final int firstItem = layoutManager.findFirstVisibleItemPositiob();
    final int lastItem = layoutManager.recyclverView.getLayoutManager().findLastVisibleItemPosition();

    int viewCount = 0;

    for (int i = firstItem; i < lastItem; i++) {
        View view = recyclerView.findViewHolderForAdapterPosition(i).itemView;
        viewCount += view.getChildCount();
    }

    return viewCount;
}

Upvotes: 1

Related Questions