I have class
public class User
{
UUID id;
String name;
}
I want to pass into ListView this: List and display only "name". But when item in list view will be selected I want to know "id" of the selected item.
I have class
public class User
{
UUID id;
String name;
}
I want to pass into ListView this: List and display only "name". But when item in list view will be selected I want to know "id" of the selected item.
First I would make a class that contains both pieces of information.
public class MyItem {
public final String name;
public final String id;
public MyItem(String name, String id) {
this.name = name;
this.id = id;
}
}
Then make a custom Adapter that can support this class.
public class CustomAdapter extends ArrayAdapter<MyItem> {
private Context context;
private ArrayList<MyItem> items;
private LayoutInflater vi;
public EntryAdapter(Context context,ArrayList<MyItem> items) {
super(context,0, items);
this.context = context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final Item i = items.get(position);
if (i != null) {
v = vi.inflate(R.layout.list_item, null); //custom xml for desired view
//do what ever you need to
}
return v;
}
}
Populate an Array of MyItem's, then crete your custom Adapter using the Array.
items = new ArrayList<MyItem>(); // then populate it
myAdapter = new CustomAdapter(this, items);
Now set up the ListView and use OnItemClickListener
myList.setAdapter(myAdapter);
myList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parentView, View view, int position,
long id)
{
((MyItem)myAdapter.getItem(position)).id); //this line gets you the id of the clicked item
}
});
store the object into an arraylist say like
Arraylist<User> al = new ArrayList<User>();
then add the objects to the arraylist using
User user = new User();
user.id = somevalue;
user.name = someNameValue;
al.add(user);
Next in the onitemclick() get the item clicked and next display it using the arraylist item
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(this, "item clicked is " + arg2+al.get(arg2).id+" "al.get(arg2).name,
Toast.LENGTH_SHORT)
.show();
}
}