When I call listview.getChildAt(index)
, what should index
be for me to get a non-null value back? Must index
be a value in the range [0, listview.getChildCount() )
or in the range [0, adapter.getCount() )
. This is a follow up question from listview count vs adapter count in android

- 1
- 1

- 13,817
- 23
- 66
- 87
4 Answers
You will need to use [0, listview.getChildCount() ) or wrap in a try/catch
because this could give you an IndexOutOfBoundsException
. However, if you are getting a null
value then it is probably because the ListView
isn't done drawing yet. You will want to post a Runnable
to solve this.
For example, this is how I get the count and decide if there are more items in the List
than what is on the screen:
listView.post(new Runnable()
{
public void run()
{
int numItemsVisible = listView.getLastVisiblePosition() -
listView.getFirstVisiblePosition();
if (itemsAdapter.getCount() - 1 > numItemsVisible && numItemsVisible > -1)
{ //do stuff }
else
{
//do other stuff
}
}
});

- 44,549
- 13
- 77
- 93
-
does the same go for getItem from the adapter? or is that, as I might expect, limited by `adapter.getCount()`? btw I will test and report back. +1 – Cote Mounyo Oct 02 '13 at 17:58
-
That will depend on the `Adapter` count, yes – codeMagic Oct 02 '13 at 18:31
ListView is just view with childrens(rows). And range for getChildAt is [0, listview.getChildCount()). ListView contains only view witch is visible now. Adapter getCount() return count of data rows, like maximum length of ListView.

- 9
- 2
per my experiment, here is how it works. The ListView is a slice of the adapter. So if an adapter has 500 items and the ListView has ten (10). The ten in the ListView represent a dynamic view. So if the firstVisibleItem were item 217 in the adapter, then the ListView range of indices would be (217,…,226) whereas the listView.getChildCount() would still return 10.
Hence the answer is:
getChildAt(x) | x : [0+firstVisibleItem, listview.getChildCount()+firstVisibleItem)

- 13,817
- 23
- 66
- 87