Adding custom data to ListView & ArrayAdapter items
I'm creating an Android application. Inside a Fragment I have a ListView
that is populated using an ArrayAdapter and an ArrayList. I'm using
android.R.layout.simple_list_item_1 for the layout for the list items. I
want to have an OnItemClickListener, so that when an item is clicked it
will show another Activity based on its data.
The problem is, there may be items with the same name. I'd like to attach
an ID value to each of the elements, so that my code can distinguish them
from each other.
My items that I use to populate the list are of a custom class to hold
their data, but the important fields here are the ID and the name (which
is shown in the ListView).
My code for populating the ListView:
List<String> items;
ArrayAdapter<String> adapter;
List<MyCustomDataObject> listOfDataObjects;
...
// Get the ListView
ListView list = (ListView) layoutRootView.findViewById(R.id.listView1);
// Create the item List and the ArrayAdapter for it
items = new ArrayList<String>();
adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, items);
// Set the list adapter
list.setAdapter(adapter);
// Add the data items
for (MyCustomDataObject obj : listOfDataObjects) {
items.add(obj.name);
}
items.add(getResources().getString(R.string.no_items));
// Create the item click listener
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
// Open the Activity based on the item
}
});
How could I add an ID to the list items for identifying each item?
No comments:
Post a Comment