Getting data from custom list view on click

android, listview

Solution

Although @Sam's suggestions will work fine in most scenarios, I actually prefer using the supplied `AdapterView` in `onItemClick(...)` for this:

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Person person = (Person) parent.getItemAtPosition(position);
    // ...
}

I consider this to be a slightly more fool-proof approach, as the `AdapterView` will take into account any header views that may potentially be added using `ListView.addHeaderView(...)`.

For example, if your `ListView` contains one header, tapping on the first item supplied by the adapter will result in the `position` variable having a value of `1` (rather than `0`, which is the default case for no headers), since the header occupies position `0`. Hence, it's very easy to mistakenly retrieve the wrong data for a position and introduce an `ArrayIndexOutOfBoundsException` for the last list item. By retrieving the item from the `AdapterView`, the position is automatically correctly offset. You can of course manually correct it too, but why not use the tools provided? :)

Just FYI and FWIW.

Problem

I have a custom ListView with two TextViews both containing different values. What I want to be able to do it get the contents from one of these TextViews when an item is clicked. This is the code I have so far: ``` listView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String value; // value = (get value of TextView here) } }); ``` I want to be able to assign `value` to the text of one of the TextView's.

Original source

Related problems