3

Why do listview.getChildCount() and adapter.getCount() return different values? I have an onScroll method and from within it, if I call the methods above, each return different values. Does anyone know why?

Cote Mounyo
  • 13,817
  • 23
  • 66
  • 87
  • Refer [this](http://stackoverflow.com/questions/10242800/android-difference-between-getcount-and-getchildcount-in-listview) – Shashank Kadne Oct 02 '13 at 17:11

2 Answers2

12

ListView.getChildCount() returns the number of Views on the screen. Adapters getCount() returns the total number of objects in your list.

getChildCount()

getCount()

You might have 50 Strings in say an ArrayAdapter but only 10 are drawn on the screen at the current moment so your ListView count will be 10 but your Adapter count will be 50.

codeMagic
  • 44,549
  • 13
  • 77
  • 93
  • If I do `listview.getChildAt(index)` must `index` be `[0,listView.getChildCount() )` or could index be anything between `[0,adapter.getCount() )`? – Cote Mounyo Oct 02 '13 at 17:37
  • `[0,listView.getChildCount() )`. Otherwise you could get `IndexOutOfBoundsException` because, like my example illustrates, you may have more items in your `List` than are currently in your `ListView` – codeMagic Oct 02 '13 at 17:46
  • Now, you could do the other way but you would need to wrap in a `try/catch` to catch the `IOB Exception` – codeMagic Oct 02 '13 at 17:47
2

adapter.getCount() returns total objects count contained in it. listView.getChildCount() return number of views showed in this listview. Adapter uses caching mechanism, and a lot of views are reused, that's why it's number differs from that shown in adapter.getCount()

Roman Bugaian
  • 354
  • 1
  • 7
  • 22