wow
wow

Reputation: 3899

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.

Upvotes: 5

Views: 11945

Answers (3)

Mr.India
Mr.India

Reputation: 674

Override following method in adaterclass.

public String[] getText() {
        return text;
    }

Upvotes: 0

MH.
MH.

Reputation: 45493

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.

Upvotes: 10

Sam
Sam

Reputation: 86948

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.)

Upvotes: 3

Related Questions