【问题标题】:How to map variable and view in android?如何在android中映射变量和视图?
【发布时间】:2015-07-03 05:03:18
【问题描述】:

我有一个对象列表,我将它们设置为查看并插入到布局中

但我不知道如何识别哪个对象的哪个视图

在我将其插入布局之前,是否可以向视图添加其他属性?

例如:

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);
}

【问题讨论】:

  • 为此使用了 setTag()getTag()

标签: android android-layout android-view layout-inflater


【解决方案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);
}

现在,每当您找到该项目时,您都可以找到类似

View view=linearlayout.getTag(hm.get(key));

【讨论】:

  • 我不明白为什么'oneItem.setTag(hm.get(key));'设置一个字符串,它返回一个视图View view=linearlayout.getTag(hm.get(key));,我想我应该使用oneItem.setTag(key),然后在每个oneItem的OnClickListener中使用hm.get(v.getTag())
  • 如果我想为视图设置更多属性呢?我试过oneItem.setTag(1,"attr1"); oneItem.setTag(2,"attr2");,但应用会崩溃
  • @CLSo 这对 HashMap 来说是不可能的。
  • 可以,我只要把对象转成字符串hm.get(v.getTag()+"")
猜你喜欢
  • 1970-01-01
  • 2013-04-11
  • 1970-01-01
  • 2023-02-14
  • 1970-01-01
  • 1970-01-01
  • 2020-09-18
  • 1970-01-01
  • 2021-11-28
相关资源
最近更新 更多