ListView setOnItemClickListener and setOnItemSelectedListener to store the Selected Item Index

我是研究僧i 提交于 2019-12-04 21:26:06

问题


I have read on this site that it is necessary to customize the setOnItemSelectedListener and setOnItemClickListener of a ListView if we want to know the Index of the SelectedItem (.getSelectedItemPosition()). So that is what I do but it does not stores the position of the SekectedItem, instead i have always -1...

What I want to do is just to give the user a way to delete items from a list by selected and Item and Clicking a button.

See the code below :

    listViewPeople.setOnItemClickListener(new ListView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> a, View v, int i, long l) {
            try {
                // Remembers the selected Index
                listViewPeopleId = listViewPeople.getSelectedItemPosition();
            }
            catch(Exception e) {
                System.out.println("Nay, cannot get the selected index");
            }
        }
    });

    listViewPeople.setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> a, View v, int i, long l) {
            try {
                // Remembers the selected Index
                listViewPeopleId = listViewPeople.getSelectedItemPosition();
                System.out.println("Yay, set the selected index " + listViewPeopleId);
            }
            catch(Exception e) {
                System.out.println("Nay, cannot get the selected index " + listViewPeopleId);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            try {
                // Remembers nothing selected
                listViewPeopleId = -1;
                System.out.println("Yay, set that nothing is selected " + listViewPeopleId);
            }
            catch(Exception e) {
                System.out.println("Nay, cannot set that nothing is selected " + listViewPeopleId);
            }
        }
    });

What's wrong??

Thank you for your help!

Christophe


回答1:


Instead of doing listViewPeople.getSelectedItemPosition(); try using the int i parameter to get the index.



来源:https://stackoverflow.com/questions/2965698/listview-setonitemclicklistener-and-setonitemselectedlistener-to-store-the-selec

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