问题描述
我正在动态创建X数量的TextView,并使用View.generateViewId()为它们提供ID。
TextView textView = new TextView(this);
textView.setText("_");
...
...
int id = View.generateViewId();
textView.setId(id);
然后我得到一些生成的ID,例如1-5,具体取决于TextViews的数量。 但是在搜索了不同的论坛和官方android网站后,我不知道如何访问这些ID。
如果我想在其中设置setText(),我该如何定位让ID = 1的TextView? 尝试了一些不同的事情,例如使用findViewById和R-class,但似乎不起作用。
感谢任何直接的帮助或相关的链接,谢谢。
1楼
声明地图:
public static final Map<String, Integer> ITEM_MAP = new HashMap<String, Integer>();
跟踪项目:
int id = View.generateViewId(); textView.setId(id); ITEM_MAP.put("key1", id); int id2 = View.generateViewId(); textView.setId(id2); ITEM_MAP.put("key2", id2);
3.然后在需要时:
int id = ITEM_MAP.get("key?X");
TextView textView = findViewById(id);
祝好运 )
2楼
如果要去地图,我建议使用与@Hovanes Mosoyan的Answers相同的方法,但不要将字符串用作键,而应将id用作键,然后将值设为textviews。
private Map<Int, TextView> textViewMap = HashMap();
...
// Add a textview to the map:
textViewMap.put(id, textView);
...
// Retrieve a textview from the map:
textViewMap.get(id);
但是,这可能会让您失望,因为视图ID不需要唯一,并且您可能会看到错误的视图。
另外,如果重复输入id,则将使用地图覆盖它,因此将获取具有相同id的最后一个视图。
所以这是一个更好的方法
使用标签。 视图有自己的标签,它们是字符串。 现在,默认情况下,视图的标签为空。 这意味着,我们可以按照自己想要的方式来操作它,并为您使用它作为唯一标识符。 现在,问题是我们如何生成唯一的ID? 使用当前时间很容易,因为时间永远不会重复。
...
int id = System.currentTimeMillis(); // Use intelli-sense, this might not be the right name of the function
textView.setTag("" + id);
...
// Retrieve the view using the tag
TextView textView = findViewWithTag("" + id);
...