动态创建的ImageView的id始终为-1

时间:2017-08-30 14:03:15

标签: android

我正在尝试将动态创建的ImageView ID存储在列表中,但始终给出-1

ImageView image = new ImageView (this);
image.getId();

4 个答案:

答案 0 :(得分:2)

从API级别17及更高版本,您可以调用View.generateViewId()并使用View.setId(int)进行设置。

答案 1 :(得分:2)

由于您尚未设置ID,因此会出现此行为。如果要识别动态添加的视图,可以通过设置标记和/或ID来实现两种方式。

标签

image.setTag("DynamicImage");

//somewhere else in the code to find this view (use rootView if fragment else its fine with just findViewWithTag method)

ImageView image = rootView.findViewWithTag("DynamicImage");

ID

 image.setId(CONSTANT_ID_VALUE);

 //somewhere else in the code to find this view (use rootView if fragment else its fine with just findViewWithTag method)
 ImageView image = rootView.findViewById(CONSTANT_ID_VALUE);

答案 2 :(得分:1)

id - 是一个唯一的名称。在获得它之前,您必须添加它。您还必须知道,所有id和s资源都只是R.class中的常量(int)。因此,如果未添加id,则为-1。

答案 3 :(得分:0)

ID通常是布局中指定的值。在以编程方式创建视图时,您有责任分配一个image.setId()。您可以使用View.generateViewId()生成un,如下所示:

image.setId(View.generateViewId());

请注意View.generateViewId()仅存在于API 17+以上。