Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a good reason for a ListView header taking up a position?

I've just added a header to my ListView and I have to change a bunch of code because the header essentially becomes position 0 (Meaning the Cursor indices of my CursorAdapter do not line up with the indicies of the list. They are off by 1 now). Why? This seems a bit silly to me.

The only reason I can come up with is that a developer may want to access the header. Fine. Provide something like getListView().getHeader().

like image 555
Andrew Avatar asked Oct 26 '10 21:10

Andrew


People also ask

What is ListView how do you use it in Android application explain with example?

Android ListView is a ViewGroup that is used to display the list of items in multiple rows and contains an adapter that automatically inserts the items into the list. The main purpose of the adapter is to fetch data from an array or database and insert each item that placed into the list for the desired result.

How do I add a header to a list view?

This example demonstrates How to add header item for Listview in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How to get data from ListView by Clicking item on ListView?

Try this: my_listview. setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { } });


1 Answers

For some reason the position (from the onItemClick) is tied up with the number of items in the ListView (not the adapter), including headers and footers. When you set an OnItemClickListener you should retrieve the clicked item by calling listView.getItemAtPosition(position) instead of adapter.getItem(position).

In fact, you should always use the getItemAtPosition, because that way not matter if your ListView has headers and footers, and if you add new headers you won't need to change your code.

And if you don't want your header to be selectable, you should add it in this way: listView.addHeaderView(headerView, null, false).

like image 91
mayconbordin Avatar answered Nov 15 '22 20:11

mayconbordin