问题
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?
回答1:
The solution is quite simple actually.
You're populating the ListView
from a List
. The List
is an ordered collection of items, so when adding it as the datasource for the ListView
you will always know the index of each item.
So when selecting an item from the ListView
you get the position of the View
clicked. This position will correspond to the position in your List
.
You won't really need the id
field of your MyCustomDataObject
, but of course when you populate the List
of MyCustomDataObject
you could use a normal for-loop (not enhanced) and use the index to set the id of each MyCustomDataObject
.
回答2:
Lookup the position in listOfDataObjects to find the ID:
// Create the item click listener
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position==listOfDataObjects.size()) { .... no_items clicked ... }
else {
MyCustomDataObject obj = listOfDataObjects.get(position);
... // Open the Activity based on the item
}
}
});
来源:https://stackoverflow.com/questions/18685232/adding-custom-data-to-listview-arrayadapter-items