Android - OnClick handler for dynamic ListView data?
I have a ListView that is filled with a dynamic set of data each time the 开发者_C百科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?
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>();
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();
// ...
}
You can also extend the ArrayAdapter to tailor the list for employee-objects: How to use ArrayAdapter<myClass>
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.
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.
精彩评论