2017-08-30 71 views
0

我试图在列表中动态创建ImageView ID,但以下总是给出-1动态创建的ImageView的ID始终为-1

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

这与预期完全相同。除非您在代码或布局XML中分配一个View,否则View没有ID。 '-1'是'View.NO_ID'。 –

+1

谢谢,这是否意味着我必须管理创建的ImageView的独特ID的创建,还是安卓API提供了一个解决方案? –

+0

也许吧。取决于你的需求。如果你以其他方式保存对'View'的引用 - 例如将它们保存到一个数组,'List'等 - 那么你不一定需要为它们分配ID。如果你需要使用'findViewById()',或者只用ID来区分'View',那么你就必须确保它们在层次结构中是唯一的关心。 –

回答

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

id - 是一个独特的名称。在你得到它之前,你必须添加它。你也必须知道,所有的id -s和资源都是R.class中的常量(int)。因此,如果id未被添加,则它是-1。

0

Id通常是布局中指定的值。当您以编程方式创建视图时,您有责任分配一个image.setId()。尽管这View.generateViewId()从API只存在17+起

image.setId(View.generateViewId()); 

注意:您可以通过使用View.generateViewId(),像这样生成联合国。

2

从API级别17及以上,你可以调用View.generateViewId()并使用View.setId(int)来设置它。