Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check if a ListView contains a specified header?

I've tried using the ListView.indexOfChild(View view) method to check if the ListView contains a specified header view, but sometimes it returns -1 when the ListView actually does contain a specified header. Is there a better way to check for this?

like image 258
Matthew Avatar asked May 29 '12 18:05

Matthew


Video Answer


1 Answers

If by 'header' you mean an actual header added using either of the addHeaderView(...) methods, you can simply retrieve the number of added headers using getHeaderViewsCount().

Alternatively, if I remember correctly, ListView will wrap its adapter inside a HeaderViewListAdapter if it contains headers and/or footers. You can use its getHeadersCount() to retrieve the same number as above.


Edit: If you want to check whether a specific header is added, you should be able to query the HeaderViewListAdapter for that. You will need some sort of criteria to check against.

For example, if there are 3 headers in your ListView, you can iterate over the first three items (you can probably grab them either directly from the HeaderListViewAdapter, or use the ListView's getItemAtPosition(...) method) and see if one matches the criteria. The easiest way to do this 'matching' is probably to add headers using the addHeaderView(...) method that also takes an Object parameter. You can supply basically anything to differentiate between the multiple headers, obviously provided that the data objects are different. E.g. you could just pass in a String.

With this data in place, you can call getItem(...)/getItemAtPosition(...) for the first 3 positions and check what gets returned. The benefit of using a String for data is that every Java object implements a toString() method, which you can then exploit for a straightforward .equals(..) comparison.

Alternatively, you could use reflection to get ahold of the actual mHeaderViewInfos member variable (which is just an ArrayList<ListView.FixedViewInfo>) and use that for the conditional logic.

like image 119
MH. Avatar answered Sep 27 '22 22:09

MH.