I'm trying to get the text of the selected item and show it in a toast message. This is the code I wrote:
final ListView lv = (ListView)findViewById(R.id.firstflightlist);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
TextView c = (TextView) arg0.findViewById(arg1.getId());
String text = c.getText().toString();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}});
The listview is a single choice listview. When I click on any item in the list, it always displays the first item of the list. What might be causing this? How can I get the selected item's text?
you don't need to findViewById, you've got the view you clicked on. also findViewById only finds the first item that matches the id, and in a list view you've got a lot of items with the same id, so it finds the first one
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
TextView c = (TextView) arg1; //<--this one
String text = c.getText().toString();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With