动态设置视图的id

Dynamically set id of a view

我必须动态创建 4 个 按钮 并且我必须动态生成它们的 ID,例如:

  for(int i = 1; i <= 4; i++){
    Button button = new Button(activity);

    // i need something here to turn this string into an int;    
    button.setId("button" + i) 
  }

我知道如何动态获取现有视图的 ID:

getResources().getIdentifier("button2", "button", getPackageName())

我不知道的是如何动态生成id。

我在网上查了一下,但没有找到任何东西。

我需要这样的东西:

int id = getResources().setIdentifier("button2", "button", getPackageName());
button.setid(id);

提前致谢。

1、在values文件夹中创建一个xml,

2、<resources> <item type="id" name="button1">123</item> </resources>

3、在java代码中使用button.setId(R.id.button1);

您可以为此使用 View.setId(int)。根据文档 id 在树层次结构中不必是唯一的,您可以使用任何(正)整数作为您以编程方式添加的 Views

医生说

The identifier does not have to be unique in this view's hierarchy. The identifier should be a positive number.

如果您想要 View 附加一些其他信息,您可以使用 setTag() 标记要查看的对象,然后按 findViewWithTag("obj");

查看

在此处查看有关创建 ID 的更多信息

更好的做法是使用在 API 17.

中引入的 button.setId(View.generateViewId())

有同样的问题,只针对 ImageView。
由于我没有找到答案,大家基本上都说了
"not possible" 或 "use xml",我创建了自己的 hashMap。