GetChildCount () and getChildAt () return zero for RecyclerView

I am trying to get the number of children RecyclerView. I tried this:

myRView.getChildCount();

And this:

LinearLayoutManager lm = ((LinearLayoutManager)myRViews.getLayoutManager());
lm.getChildCount();

I need the child to look at a certain position, so I need this. If I call getChildAt(index), I never get a child view.

Both of these methods return 0. How else to get the child view from the RecyclerView? My items are displayed correctly and everything is working fine. I call these methods after creating my adapter and installing it in the RecyclerView. Thank you for your help.

+5
source share
4 answers

I assume that you call these methods before calculating the layout.

, . ViewTreeObserver.

+4

getItemCount() .

myRView.getAdapter.getItemCount();
+6

The function is called when the view is not ready for why it returns zero, the post () method will help.

myRView.post(new Runnable() {
        @Override
        public void run() {
            Log.show("myRView.post " + myRView.getChildCount());
            View childView = myRView.getChildAt(0);
        }
    });
+1
source

getChildCount() can return 0 if you forget to set the LayoutManager in the RecyclerView.

myRView.setLayoutManager(mLayoutManager);
0
source

All Articles