0

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

Community
  • 1
  • 1
Cote Mounyo
  • 13,817
  • 23
  • 66
  • 87

4 Answers4

2

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
        }               
    }
});
codeMagic
  • 44,549
  • 13
  • 77
  • 93
0

That would be [0, listview.getChildCount() )

Thijs Mergaert
  • 399
  • 3
  • 4
0

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.

0

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)
Cote Mounyo
  • 13,817
  • 23
  • 66
  • 87