Skip to content Skip to sidebar Skip to footer

Listview Onitemclick Only Gets The First Item

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

Solution 1:

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(newOnItemClickListener() {

    @OverridepublicvoidonItemClick(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {


        TextViewc= (TextView) arg1; //<--this one Stringtext= c.getText().toString();
        Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();               
    }});

Solution 2:

You are getting the arg0 which is the AdapterView. You should get arg1 instead which refers to the clicked view.

Stringtext = ((TextView) arg1).getText();

parent The AdapterView where the click happened. view The view within the AdapterView that was clicked (this will be a view provided by the adapter) position The position of the view in the adapter. id The row id of the item that was clicked.

publicabstractvoidonItemClick(AdapterView<?> parent, 
                                  View view, 
                                  int position, 
                                  long id)

See AdapterView.OnItemClickListener

Solution 3:

@OverridepublicvoidonItemClick(AdapterView<?> parent, View view, int position,
            long id) {

        Stringtext= (String) parent.getItemAtPosition(position);
        Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();               
    }});

assuming that your ListView is filled up with String

Solution 4:

As I feel that list view having the items then, can directly use below line inside onClick() method to get selected text from the list view:

Stringtext = (String) adapterView.getItemAtPosition(position);

This will give the selected text from the list view and can be used everywhere.

Post a Comment for "Listview Onitemclick Only Gets The First Item"