How to know the max amount of ItemViews that can be visible in the RecyclerView without loading the data?

Viewed 1446

I have a paging algorithm for the RecyclerView, which if done Scroll, a scrolling listener triggers and loads more elements. Initially, I assigned a number of elements to load in the request to the server by default that is 20 for my RecyclerView, which has a fixed size (not wrap_content).

I need to know the number of items that can be visible in the width/height of the defined RecyclerView before loading the data, to determine the amount of items to be requested in the initial load, given that with 20 items on some devices is not enough to activate the listener of the scroll and load more elements.

This is without considering the extra properties of the view, such as padding, margin etc ...

The solution can be in Java Android or Xamarin Android (not Forms) C#.

Update:

For you to have a clue, i have tried this and it works for me, only if I call it when the size of RecyclerView is assigned, inside the OnLayoutChange:

public int GetMaxVisibleItemCountFromRecyclerView(RecyclerView recyclerView)
{
             if (recyclerView == null) return 0;

             int Width = recyclerView.Width;
             int Height = recyclerView.Height;

             if (Width == 0 || Height == 0)
                return 0;

             var layoutManager = recyclerView.GetLayoutManager() as GridLayoutManager;

             if (layoutManager == null) return 0;

             int widthRatio = Width / layoutManager.SpanCount;
             int quantity = (Height / widthRatio) * layoutManager.SpanCount;

             return quantity;

}

This solution only works for RecyclerViews that use the GridLayoutManager. I have other RecyclerViews with defined sizes that also use the paging algorithm with a LinearLayoutManager.

I need a similar solution, that works with any LayoutManager of the RecyclerView and does not have to be called inside the OnLayoutChange, is this possible?

2 Answers

Instead of trying to replicate the computations that RecyclerView does to compute layout, let the system do the work for you. The following example lets RecyclerView lay out one item and measurements are taken from that. The dummy item is not displayed and is used just for measurement.

The advantage of this method is that we don't have to replicate what RecyclerView does to measure items. All key measurements are taken into account including padding, margins and decorations.

The following sample shows how this can be accomplished for GridLayoutManager and LinearLayoutManager. StaggeredGridLayoutManager and FlexboxLayoutManager are special cases and aren't taken into account here.

Here is a short video showing the results of this demo app showing that just one page of items was loaded.

enter image description here

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private List<String> mItems = new ArrayList<>();
    private RecyclerView mRecycler;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecycler = findViewById(R.id.recyclerView);

        // Sample for vertical LinearLayoutManager.
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);

        // Sample for GridLayoutManager with 4 spans. Each item comsumes 2 spans.
//        GridLayoutManager layoutManager = new GridLayoutManager(this, 4);
//        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
//            @Override
//            public int getSpanSize(int position) {
//                return 2;
//            }
//        });

        // Add single dummy item that will be measured but not be displayed.
        mItems.add("Dummy item");
        RecyclerViewAdapter mAdapter = new RecyclerViewAdapter(mItems);
        mRecycler.setLayoutManager(layoutManager);
        mRecycler.setAdapter(mAdapter);

        // Take measurements in OnPreDraawListener(). This could also be accomplished with
        // mRecyclerView.post(new Runnable()...)
        mRecycler.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                mRecycler.getViewTreeObserver().removeOnPreDrawListener(this);

                // RecyclerView is laid out with single dummy entry. Get how many of this type
                // of item can fit into the visible portion of the RecyclerView.
                final int nItems = getInitialLoadCount(mRecycler);
                Log.d(TAG, "<<<<Items per page=" + nItems);

                // Don't need the dummy entry any more.
                mItems.clear();
                mRecycler.getAdapter().notifyDataSetChanged();
                mItems = new ArrayList<>();

                // Fake load...
                loadInitialItems(nItems);
                return false;
            }
        });
    }

    // Determine how many items will fill one screen of the RecyclerView. Call with the
    // RecyclerView loaded with at least one item for measurement.
    private int getInitialLoadCount(RecyclerView recyclerView) {
        int itemsToLoad = 0;
        RecyclerView.LayoutManager lm = recyclerView.getLayoutManager();
        View firstChild = recyclerView.getChildAt(0);

        if (lm instanceof LinearLayoutManager) {
            Rect bounds = new Rect();
            recyclerView.getDecoratedBoundsWithMargins(firstChild, bounds);
            if (lm.canScrollVertically()) {
                int recyclerHeightForItems = recyclerView.getHeight() - recyclerView.getPaddingTop()
                    - recyclerView.getPaddingBottom();
                itemsToLoad = (recyclerHeightForItems + bounds.height() - 1) / bounds.height();
            } else if (lm.canScrollHorizontally()) {
                int recyclerWidthForItems = recyclerView.getWidth() - recyclerView.getPaddingLeft()
                    - recyclerView.getPaddingRight();
                itemsToLoad = (recyclerWidthForItems + bounds.width() - 1) / bounds.width();
            }
            if (lm instanceof GridLayoutManager) {
                // Adjust for GridLayoutManager. All items should to be the same number of spans.
                GridLayoutManager glm = (GridLayoutManager) lm;
                itemsToLoad *= glm.getSpanCount() / glm.getSpanSizeLookup().getSpanSize(0);
            }
        }
        return itemsToLoad;
    }

    private void loadInitialItems(final int itemCount) {
        // Simulate load of nItems...should be on non-UI thread.
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= itemCount; i++) {
                    sleep(250);
                    mItems.add("Item #" + i);
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mRecycler.swapAdapter(new RecyclerViewAdapter(mItems), true);
                    }
                });
            }
        }).start();
    }

    private static final String TAG = "MainActivity";
}

If your RecyclerView and your item width and height are defined in dp, then you should save their dimensions in dimen.xml. Then you can calculate how many items will fit like this:

float recyclerHeight = getResources().getDimension(R.dimen.recycler_height);
float itemHeight = getResources().getDimension(R.dimen.item_height);
int numOfItemsFit = (int) (recyclerHeight / itemHeight);

If your recyclerView isn't defined by dp, but the rest of the views in this layout are you can try to accomplish the same thing by decreasing the other views height from the total view height. You can check the total view height with:

 public int getHeight() {
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    return size.y;
}

If you can't do the above you'll need to measure your RecyclerView inside of OnLayoutChange :( . You can do that with: recyclerView.getMeasuredHeight(); and recyclerView.getMeasuredWidth();

Related