Android - 动态 ListView 数据的 OnClick 处理程序?
我有一个 ListView,每次创建 Activity 时都会填充一组动态数据。为了简单起见,假设每个 ListView 项目都是员工的姓名。在幕后,每个员工都有一个 employee_id
号码。该号码在界面中的任何位置都看不到。
当我在 ListView 中单击员工姓名时,我想启动另一个 Activity,将相应员工的 employee_id
传递给该 Activity。
我了解如何实现 ListView 的 onClick 处理程序。我的问题是,我将在哪里存储和检索每个员工的 employee_id
?我是否可以将其与员工出现的列表中的位置一起存储在哈希/映射中?当我点击时,我只需确定我点击的列表中的位置,然后使用该位置从哈希中获取employee_id
?
I have a ListView that is filled with a dynamic set of data each time the Activity is created. For simplicity's sake, lets say each ListView item is a employee's name. Under the hood, each employee has an employee_id
number. This number is not visible anywhere in the interface.
When I click on an employee's name in the ListView, I want to launch another activity, passing the corresponding employee's employee_id
to that Activity.
I understand how to implement the onClick handler for the ListView. My question is, where would I store and retrieve the employee_id
for each employee? Would I simply store it in a hash/map along with the position in the list that the employee shows up at? And when I click, I just determine the position in the list I clicked at, and then get the employee_id
from the hash using that position?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将 ArrayAdapter 与员工列表一起使用 - 假设您有员工对象。
然后使用 OnItemClick 中的位置参数来获取员工对象。
您还可以扩展 ArrayAdapter 来定制员工对象的列表:
如何使用 ArrayAdapter
Use the ArrayAdapter with a list Employees - assuming you have Employee-object.
Then use the position parameter in OnItemClick to get the employee-object.
You can also extend the ArrayAdapter to tailor the list for employee-objects:
How to use ArrayAdapter<myClass>
您可以基于某些数据集(例如,Employee 对象列表)使用适配器。当您在 ListView 上设置 onItemClickListener 时,onItemClick 方法会获取一个 int 参数,该参数是基础数据中的位置。使用它从列表中提取 Employee 对象,这就是员工 ID。
You use an Adapter based on some set of data (for example, a List of Employee objects). When you set an onItemClickListener on your ListView, the onItemClick method gets an int parameter that is the position in the underlying data. Use that to pluck the Employee object out of your List, and there's the employee id.
我建议按照你上面说的做。或者,我真的不认为这是一个很好的解决方案,我也认为没有任何解决方案,但是您可以添加一个没有内容的标签(maxHeight和maxWdith都是0,或者不可见?从未尝试过)并设置文本。我不知道它是如何资源明智的。但您不必再保存列表,如果您有一个大列表,这可以节省一些内存。
I would suggest doing what you stated above. Or, I don't really think it's nice solution, I also think there aint any, but you could add a label with no content (maxHeight and maxWdith are both 0, or invisible? never tried that) and set the text. I don't know how it is resource wise. But you won't have to save the list anymore, which saves some memory if you have a big list.