Dynamic allocation of widget ID’s

In my Mosaic class one of the things I had to do was create a palette of Facebook friends profile pictures. I drew each profile picture as an ImageView inside a scrolling horizontal linear layout. This is easy enough to do, just dynamically create new ImageViews. However I had to be able to reference them by an ID number. What I decided to do was start at an arbitrary id value, say id=200, and go from there. So friend 1’s id=200, friend 2’s id=201, etc. Of course, what if that ID was taken? I took care of this by writing a find valid ID function. Here is how you check if an ID is taken:
int id = 200+idoff;
// Returns a valid id that isn’t in use
View v = findViewById(id);
while (v != null){
v = findViewById(++id);
}
return id;
Now you have an ID where the View is null, this is a free ID. Now you just need to assign it to your ImageView.
tile.setId(id);

This allows you to have a bunch of one widget dynamically without statically defining each one in the XML code.

About Rick Tilley

FSU in computer science from 2012 to 2014. I'm a student there, and am interested in developing Android apps.