Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 626
ManahManah Avatar asked Dec 16 '22 10:12

ManahManah


1 Answers

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();               
    }});
like image 200
Lena Bru Avatar answered Jan 10 '23 23:01

Lena Bru