Calling methods on objects in a ListView
I have a listview that is populated by a by objects from an "Offer" class I've written. Obviously, the toString()
method is called and that's the text that's displayed in each list item. My question is, how do I implement an onItemClickListener
that will call one of my getter or setter methods on the particular object whose toString method had been used to populate that item?
For example, I'd like to raise a toast or something when an item is clicked that retrieves a string my getClaimCode()
method and displays in the toast (or whatever other dialog or even a new activity).
can I开发者_StackOverflow社区 just call the methods by doing something like item.getClaimCode()
...?
You don't have to implement AdapterView.OnItemClickListener, but I do, and in onCreate() I call myListView.setOnItemClickListener(this).
Then for the AdapterView.OnItemClickListener interface, I have the method:
@Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
//Code
}
For you, you might do something like:
@Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
//Arg2 is the position in the list so...
OfferObject offer = (OfferObject) arg0.getItemAtPosition(arg2);
//Go to town...
}
Of course your Activity doesn't have to implement the AdapterView.OnItemClickListener and you could create the listener on the fly.
yourList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
OfferObject offer = (OfferObject) arg0.getItemAtPosition(arg2);
//Same idea here...
}
});
精彩评论