如何从 ListView 中获取所选项目? [英] How to get the selected item from ListView?
问题描述
在我的 Android 应用程序中,我创建了一个名为 myList 的 ListView 组件,并用我自己的自定义类型的对象填充它:
in my Android app I have created a ListView component called myList, and filled it with objects of my own custom type:
class MyClass{
private String displayName;
private String theValue;
... //here constructor, getters, setters and toString() are implemented
}
我使用 ArrayAdapter 将 ArrayList theObjects 与 myList 绑定:
I used the ArrayAdapter to bound the ArrayList theObjects with myList:
ArrayAdapter<MyClass> adapter=
new ArrayAdapter<MyClass>(this, R.layout.lay_item, theObjects);
myList.setAdapter(adapter);
这很好用,列表已填充等等,但是当我尝试访问所选项目时,我收到一个 Null 对象.我已经使用
This works fine, the list is populated and etc., but when I'm trying to access the selected item, i receive a Null object. I've done this using
myList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
MyClass selItem = (MyClass) myList.getSelectedItem(); //
String value= selItem.getTheValue(); //getter method
}
似乎是什么问题?谢谢
推荐答案
默认情况下,当您单击 ListView 项时,它不会将其状态更改为已选择".所以,当事件触发而你这样做时:
By default, when you click on a ListView item it doesn't change its state to "selected". So, when the event fires and you do:
myList.getSelectedItem();
该方法没有任何返回值.你要做的是使用位置并通过以下方式获取底层对象:
The method doesn't have anything to return. What you have to do is to use the position and obtain the underlying object by doing:
myList.getItemAtPosition(position);
这篇关于如何从 ListView 中获取所选项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!