Android ListView setOnItemClickListener 和 setOnItemSelectedListener 来存储选中项索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2965698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ListView setOnItemClickListener and setOnItemSelectedListener to store the Selected Item Index
提问by Christophe
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...
我在这个站点上读到,如果我们想知道 SelectedItem (.getSelectedItemPosition()) 的索引,则有必要自定义 ListView 的 setOnItemSelectedListener 和 setOnItemClickListener。所以这就是我所做的,但它不存储 SekectedItem 的位置,而是我总是 -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
克里斯托夫
回答by sgarman
Instead of doing listViewPeople.getSelectedItemPosition();
try using the int i parameter to get the index.
而不是listViewPeople.getSelectedItemPosition();
尝试使用 int i 参数来获取索引。