Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting data from custom list view on click

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.

like image 343
Dan Avatar asked Dec 24 '12 00:12

Dan


2 Answers

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.

like image 128
MH. Avatar answered Oct 20 '22 00:10

MH.


You have a few options. I reference the code from your previous question.

  • You can access this data from the row's layout view:

    ViewHolder holder = (ViewHolder) view.getTag();
    // Now use holder.name.getText().toString() and holder.description as you please
    
  • You can access the Adapter with position:

    Person person = mAdapter.getItem(position);
    // Now use person.name and person.description as you please
    

(By the way in your Person class, name and description are public so you don't need the get methods.)

like image 23
Sam Avatar answered Oct 20 '22 00:10

Sam