Skip to content Skip to sidebar Skip to footer

Android - Assign And Retrieve Id's Dynamically

I know how to assing ID's dynamically by invoking setID(). For the ID's to be unique, I used to utilize ids.xml and pass to setID() ID's from the pre-generated pool of ID's. Questi

Solution 1:

From API level 17 you can get a new id by calling

View.generateViewId()

Details here.

Solution 2:

Is there any way to assign ID's without utilizing the ids.xml since I cannot anticipate how many ID's I will need in runtime?

This guarantees that every view has a unique ID

for(int i =0 ; i < yourIDcount ; i++){
yourView.setId(i);
}

how can the view be retrieved when the ID is known?

View.findViewById(yourView.getId());

can be used to get your view's id, since every view has a unique Id you can get back the view you wanted..

The word dynamic means which is created at runtime, since you assign id in onCreate it is assigned as the views id, since onCreate is called only once an activity is created, you can make sure that the id you assigned stays intact...

Post a Comment for "Android - Assign And Retrieve Id's Dynamically"