ListView onItemClick gets only the first item

I am 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(); }}); 

A list is the only listview list. When I click on any item in the list, it always displays the first item in the list. What could be the reason for this? How to get selected element text?

+4
source share
3 answers

you don't need findViewById, you have the view you clicked on. also findViewById finds only the first element that matches the identifier, and in the list view you have many elements with the same identifier, so it finds the first

  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(); }}); 
+6
source

You get arg0 , which is an AdapterView . You should get arg1 instead, which refers to the view being viewed.

 String text = ((TextView) arg1).getText(); 

parent AdapterView where the click occurred.
performance . The view in the adapter window that was clicked (this will be the view provided by the adapter)
position View position in the adapter.
id The identifier of the row of the item that was clicked.

 public abstract void onItemClick (AdapterView<?> parent, View view, int position, long id) 

See AdapterView.OnItemClickListener

+3
source
  @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String text = (String) parent.getItemAtPosition(position); Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show(); }}); 

assuming your ListView is populated with String

+2
source

Source: https://habr.com/ru/post/1485291/


All Articles