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
Solution 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
.
Solution 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
}
}
});
Post a Comment for "Adding Custom Data To ListView & ArrayAdapter Items"