如何从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
}
我来约束的ArrayList theObjects与myList上一个ArrayAdapter:
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);
这工作得很好,在列表中填充等,但是当我试图进入所选的项目,我收到一个空的对象。我做这个使用
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
}
似乎什么问题吗?谢谢
What seems to be the problem? Thank you
推荐答案
在默认情况下,当你点击一个ListView项不为选择改变了他的状态,因此,当事件触发时,你做的:
By default, when you click on a ListView item it doesn't change his 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 underlaying object by doing:
myList.getItemAtPosition(position)
这篇关于如何从ListView中选定的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!