帮助解决一个简单的 Android ListView 问题
我是 Android 新手,所以这似乎是一个基本问题。但我得到的是一个非常简单的类,称为 SingleItem,它有一个整数和一个字符串,以及每个类的 getter 和 setter。在我的应用程序中,我得到了一个 ArrayList,它包含 SingleItem 对象的集合。我还有一个带有 ListView 小部件的布局。
我想做的是用 SingleItem 中的 String 值填充 ListView,但是当用户从 ListView 中选择一个项目时,我需要该 SingleItem 值中的整数 ID。在 Android 开发中如何做到这一点?
I am new to Android, so this may seem like a basic question. But what I got is a very simple class called SingleItem, which has an integer and a String and a getter and setter for each. In my application, I got an ArrayList which holds a collection of SingleItem objects. I also have a layout with a ListView widget.
What I am trying to do is populate the ListView with my String value in SingleItem, but when a user selects an item from the ListView, I need the integer ID from that SingleItem value. How do I do this in Android development?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用自己的适配器来填充列表,那么在构建要返回的视图时的 getView() 函数中,您可以调用 setTag() 在您返回的视图上并存储整个“SingleItem”对象。然后,在返回的视图的 onClickListener 中,您可以使用已单击视图的 getTag() 方法检索信息。
编辑:
指定我指的是哪个 onClickListener
If you are using your own adapter to populate the list then in the getView() function when building the view to return you can call setTag() on the view you are returning and store the entire "SingleItem" object. Then in the onClickListener of the views you return you can retrieve your info using the getTag() method of the view that has been clicked.
EDIT:
Specified which onClickListener I am referring to
这是一堆伪代码:创建您自己的适配器。这将提供执行各种操作的灵活性,但对您来说重要的是仅显示自定义类中的相关字段并创建更复杂的列表视图。一个不错的教程在这里:http://developerlife.com/tutorials/?p=327
您将必须处理 baseadapter 的其他重写,但关键是分配 singleItem.getString() 的值。
定义自定义适配器后,您可以将其分配给 listview 并将侦听器分配给 OnItemSelectedListener。由于这会返回位置,因此您可以将其与 SingleItems 的 ArrayList 中的位置联系起来。
here is a bunch of pseudo code: create your own adapter. This will give the flexibility to do all kinds of things but important to you here is displaying only the relevant fields from your custom class and make more complicated listviews. a decent tutorial is here: http://developerlife.com/tutorials/?p=327
You will have to handle the other overrides of baseadapter but the key is assigning the value of singleItem.getString()
After defining your custom adapter, you can then assign it to the listview and assign a listener to the OnItemSelectedListener. since this returns the position, you can tie that back to the position in your ArrayList of SingleItems.