Dynamically generate IDs for Views in Android

by Sasikumar 2014-04-26 10:19:45

Dynamically generate IDs for views in android :
To generate ids dynamically for views in android without id conflicts use the following function,
private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
@SuppressLint("NewApi")
public static int generateViewId() {
if (Build.VERSION.SDK_INT < 17) {
for (;;) {
final int result = sNextGeneratedId.get();
// aapt-generated IDs have the high byte nonzero; clamp to the range under that.
int newValue = result + 1;
if (newValue > 0x00FFFFFF)
newValue = 1; // Roll over to 1, not 0.
if (sNextGeneratedId.compareAndSet(result, newValue)) {
return result;
}
}
} else {
return View.generateViewId();
}
}

In this function if API level is greater than 17 then the function will use the inbuild generateViewId() function to create the id, else it will generate ids smaller than 0x00FFFFFF as ids greater than this value is assigned for the default android resources.
750
like
0
dislike
0
mail
flag

You must LOGIN to add comments