Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value of item on OnItemClick Listview

I try to get the value of a selected Item within a custom adapter on a listview. I try this with following code:

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

                    View curr = parent.getChildAt((int) id);
                    TextView c = (TextView)curr.findViewById(R.id.tvPopUpItem);
                    String playerChanged = c.getText().toString();

                    Toast.makeText(Settings.this,playerChanged, Toast.LENGTH_SHORT).show();

                }

At the beginning, if I click, the values are good, but once I scrolled and I click on another Item, I get the wrong value of that clicked item... Any idea what is causing this?

like image 488
Matthias Vanb Avatar asked Nov 15 '12 20:11

Matthias Vanb


1 Answers

The parameter v is the current row. so use:

public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    TextView c = (TextView) v.findViewById(R.id.tvPopUpItem);
    String playerChanged = c.getText().toString();

    Toast.makeText(Settings.this,playerChanged, Toast.LENGTH_SHORT).show();
}

(Or you could use getChildAt(position) but this would be slower.)

Understand you might be able to simplify this more depending on your layout.

like image 96
Sam Avatar answered Oct 12 '22 23:10

Sam