Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android RecyclerView wrong childCount

I created a simple RecyclerView with an adapter and sometimes I need to get the count of child views in my RecyclerView outside the adapter.

I use: ((LinearLayoutManager) myRecyclerView.getLayoutManager()).getChildCount() for this. But I never get the real count of views inside the RecyclerView.

For example, I add 10 items to my list and call adapter.notifyDataSetChanged(). After this I call ((LinearLayoutManager) myRecyclerView.getLayoutManager()).getChildCount() I get 4.

Can someone explain me how to get the real count of views inside the RecyclerView?

like image 419
TopAd Studio Avatar asked Oct 20 '25 21:10

TopAd Studio


1 Answers

You get the real count of views. If adapter has 10 items and ((LinearLayoutManager) myRecyclerView.getLayoutManager()).getChildCount() returns you 4, there is nothing wrong with that.

The count of items in the model (adapter) and the count of views are not the same thing.

RecyclerView doesn't hold views for all 10 items in memory, it only has 4 in your case. When you scroll, it reuses those 4 views for displaying different items. The purpose of this is improving the rendering performance.

If you want to get 10, then you should use adapter.getCount() instead.

like image 141
Gennadii Saprykin Avatar answered Oct 22 '25 10:10

Gennadii Saprykin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!