Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getChildCount() and getChildAt() return zero for RecyclerView

I am trying to get a count of RecyclerView children. I've tried this:

myRView.getChildCount();

And this:

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

I need to get a child View at certain position so that's why I need this. If I call getChildAt(index) I never get any child View.

Both of these methods return 0. How else to get a child View from RecyclerView? My items appear correctly and everything is working fine. I am calling these methods after I create my adapter and set it to RecyclerView. Thank you for your help.

like image 852
user3304086 Avatar asked Feb 13 '15 17:02

user3304086


3 Answers

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

myRView.post(new Runnable() {
        @Override
        public void run() {
            Log.show("myRView.post " + myRView.getChildCount());
            View childView = myRView.getChildAt(0);
        }
    });
like image 100
thanhbinh84 Avatar answered Nov 05 '22 16:11

thanhbinh84


I assume you are calling those methods before layout is calculated.

When you set the adapter, the layout will happen in the next view tree traversal. You can consider adding a ViewTreeObserver.

like image 7
yigit Avatar answered Nov 05 '22 15:11

yigit


You could use your adapter getItemCount() function.

myRView.getAdapter.getItemCount();
like image 7
Jofre Mateu Avatar answered Nov 05 '22 16:11

Jofre Mateu