Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed extra information in a View in android?

Tags:

android

I am beginning android development and in my sample application I have a ListView which I populate as follows:

ListView listView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getEntityLabels());
listView.setAdapter(adapter);

The getEntityLabels() is a function that returns a list of strings.

In the underlying model, the labels are not unique. Instead each entity has an id field which is unique for every entity.

class Entity{
  int id;
  String label;
}

When the user clicks on an item in the ListView, I would like to do some processing. So, I added an ItemClickListener as follows:

listView.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) 
{               
      //I would like to get the Id of the Entity, not just the label
}});

The processing depends on the id of the entity. However, as the view in the list is just a text and contains only the label, I cannot access it.

Is there a way to embed some information like id(in my case) with the views or an alternate way to get the ids?

I am aware of the way where I can override the toString() method of Entity to return label and use ArrayAdapter<Entity> instead of ArrayAdapter<String>. However, I am not looking for this. I am looking for a more generic way where I can embed any information with any View, if possible!

like image 637
Ankit Avatar asked Dec 27 '25 16:12

Ankit


1 Answers

You can use tags and assign tag to each view set in your adapter. Then you can read your tag from clicked view in OnClickListener and proceed. As tag can be anything (Object) you like that should solve your problem. See setTag() and related.

like image 73
Marcin Orlowski Avatar answered Dec 31 '25 17:12

Marcin Orlowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!