ListView onItemClick only gets the first item

我的梦境 提交于 2020-01-03 15:32:10

问题


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?


回答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(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();               
    }});



回答2:


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

String text = ((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.

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

See AdapterView.OnItemClickListener




回答3:


    @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 that your ListView is filled up with String



来源:https://stackoverflow.com/questions/17010870/listview-onitemclick-only-gets-the-first-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!