This is the description given for the setId() method.
void android.view.View.setId(int id)public void setId (int id)
Since: API Level 1
Sets the identifier for this view. The identifier does not have to be
unique in this view’s hierarchy. The identifier should be a positive
number.
My question is, why does the identifier not have to be unique in this view’s hierarchy though we assign unique ids in an XML file?
The
android:iddoes not have to be unique in the XML file, either, though that is the way you write it, typically.To understand why a widget ID does not need to be unique, consider the
ListView. Let’s say that we have aListViewwith 8 rows. Each of those rows is created by inflating a layout XML resource (e.g.,android.R.layout.simple_list_item_1). Each of those inflated rows are children of theListView. Yet, since each of those rows is inflated from the same layout resource, each row’s widgets have the same IDs as all the other rows.This is not generally a problem. It does lead to one cardinal rule of Android development: always call
findViewById()on something that will give you a unique result for the widget you seek. In this case, I do not want to callfindViewById()on theListViewor theActivityto find a widget inside of one of the rows, as there will be 8 widgets all with the same ID, and I do not know which row’s widget I will get back. Instead, I need to callfindViewById()on the row, to get the particular widget from that specific row.