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?
I’ve tried using the ListView.indexOfChild(View view) method to check if the ListView contains a
Share
If by ‘header’ you mean an actual header added using either of the
addHeaderView(...)methods, you can simply retrieve the number of added headers usinggetHeaderViewsCount().Alternatively, if I remember correctly,
ListViewwill wrap its adapter inside aHeaderViewListAdapterif it contains headers and/or footers. You can use itsgetHeadersCount()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
HeaderViewListAdapterfor 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 theHeaderListViewAdapter, or use theListView‘sgetItemAtPosition(...)method) and see if one matches the criteria. The easiest way to do this ‘matching’ is probably to add headers using theaddHeaderView(...)method that also takes anObjectparameter. 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 atoString()method, which you can then exploit for a straightforward.equals(..)comparison.Alternatively, you could use reflection to get ahold of the actual
mHeaderViewInfosmember variable (which is just anArrayList<ListView.FixedViewInfo>) and use that for the conditional logic.