Skip to content Skip to sidebar Skip to footer

Confusion With Setid() Method In Android

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

Solution 1:

My question is, why does the identifier not have to be unique in this view's hierarchy though we assign unigue id in xml file..?

The android:id does 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 a ListView with 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 the ListView. 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 call findViewById() on the ListView or the Activity to 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 call findViewById() on the row, to get the particular widget from that specific row.

Solution 2:

IDs need not to be unique, you can use any positive integer you like, but in this case there can be some views with equivalent id's.

Also Like Romain Guy Said in this post:

findViewById() is a depth-first search algorithm; it will return the first view of the specified id it can find.

Post a Comment for "Confusion With Setid() Method In Android"