If you use OnGlobalLayoutListener , you must remember that onGlobalLayout can be called several times. Some of these calls may occur before the Layout is ready (and ready, I mean the moment when you can get the View dimensions by calling view.getHeight() or view.getWidth() ). So the correct way to implement your approach is:
recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { int width = recyclerView.getWidth(); int height = recyclerView.getHeight(); if (width > 0 && height > 0) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { recyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } else { recyclerView.getViewTreeObserver().removeGlobalOnLayoutListener(this); } } View firstRecyclerViewItem = recyclerView.getLayoutManager().findViewByPosition(0); } });
In addition, you should still be sure that during the call to findViewByPosition(0) :
- Your
RecyclerView's Adapter has at least one data item. View at position 0 is currently displayed in RecyclerView
Tell me if this fixes your problem, if there is no other way to do what you need.
Bartek lipinski
source share