Android-动态ListView数据的OnClick处理程序? [英] Android - OnClick handler for dynamic ListView data?
问题描述
我有一个ListView,每次创建Activity时,它都会填充一组动态数据.为了简单起见,可以说每个ListView项目都是员工的名字.在幕后,每个员工都有一个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.
当我在ListView中单击某个员工的姓名时,我要启动另一个活动,将相应员工的employee_id
传递给该活动.
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.
我了解如何为ListView实现onClick处理程序.我的问题是,我应该在哪里存储和检索每个员工的employee_id
?我是否只需将其与员工显示在列表中的位置一起存储在哈希/映射中?当我单击时,我只是确定单击列表中的位置,然后使用该位置从哈希中获取employee_id
?
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?
推荐答案
将ArrayAdapter与雇员"列表一起使用-假设您有Employee-object.
Use the ArrayAdapter with a list Employees - assuming you have Employee-object.
public class MyActivity extends ListActivity {
// list of employees
private List<Employee> employees = new ArrayList<Employee>();
然后使用OnItemClick中的position参数获取员工对象.
Then use the position parameter in OnItemClick to get the employee-object.
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int employee_id = ((Employee) getListAdapter().getItem(position)).getId();
// ...
}
您还可以扩展ArrayAdapter来定制员工对象的列表: 如何使用ArrayAdapter< myClass>
You can also extend the ArrayAdapter to tailor the list for employee-objects: How to use ArrayAdapter<myClass>
这篇关于Android-动态ListView数据的OnClick处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!