Skip to content

Instantly share code, notes, and snippets.

@omegasoft7
Created January 9, 2015 09:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omegasoft7/fdf7225a5b2955a1aba8 to your computer and use it in GitHub Desktop.
Save omegasoft7/fdf7225a5b2955a1aba8 to your computer and use it in GitHub Desktop.
SetID to a View Programmatically
Google finally realized the need of generating unique IDs for programmatically created views...
From API level 17 and above, you can call
View.generateViewId()
Then use View.setId(int).
In case you need it for targets lower than level 17, here is its internal implementation in View.java you can use directly in your project, put it in your util class or somewhere:
private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
/**
* Generate a value suitable for use in {@link #setId(int)}.
* This value will not collide with ID values generated at build time by aapt for R.id.
*
* @return a generated ID value
*/
public static int generateViewId() {
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;
}
}
}
ID number larger than 0x00FFFFFF is reserved for static views defined in the /res xml files. (Most likely 0x7f****** from the R.java in my projects.)
In your code, you can do:
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
myView.setId(Utils.generateViewId());
} else {
myView.setId(View.generateViewId());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment