-2

I have a list of objects, I set them to view and insert to layout

But I don't know how to identify which view for which object

Is it possible to add additional attribute to view before I insert it to layout?

For example:

LayoutInflater inflater=LayoutInflater.from(this);

HashMap<String, String> hm=new HashMap<String, String>();
hm.put("key1", "value 1");
hm.put("key2", "value 2");
hm.put("key3", "value 3");

for(String key: hm.keySet())
{
    View oneItem=inflater.inflate(R.layout.oneItem, linearlayout, false);
    TextView tv=(TextView)oneItem.findViewById(R.id.value);
    tv.setText(hm.get(key));

    //Is there any something like this?
    //oneItem.putExtra("id", key);
    //oneItem.setAttribute("id", key);

    linearlayout.addView(oneItem);
}
CL So
  • 3,647
  • 10
  • 51
  • 95

1 Answers1

1
for(String key: hm.keySet())
{
    View oneItem=inflater.inflate(R.layout.oneItem, linearlayout, false);
    TextView tv=(TextView)oneItem.findViewById(R.id.value);
    tv.setText(hm.get(key));

    oneItem.setTag(hm.get(key));

    linearlayout.addView(oneItem);
}

Now whenever you find that item you can find like

View view=linearlayout.getTag(hm.get(key));
Mohd Mufiz
  • 2,236
  • 17
  • 28
  • I don't understand why 'oneItem.setTag(hm.get(key));' set a string, and it return a view `View view=linearlayout.getTag(hm.get(key));`, I think I should use `oneItem.setTag(key)`, and then use `hm.get(v.getTag())` in OnClickListener of each oneItem. – CL So Jul 03 '15 at 05:31
  • How about if I want to set more attribute to the view? I tried `oneItem.setTag(1,"attr1"); oneItem.setTag(2,"attr2");`, but the app will crash – CL So Jul 03 '15 at 05:34
  • @CLSo That's not possible with `HashMap`. – M D Jul 03 '15 at 05:48
  • That is possible, I just need to convert the object to string `hm.get(v.getTag()+"")` – CL So Jul 03 '15 at 06:31