Jeśli chodzi o rozwiązanie awaryjne dla API < 17, widzę, że proponowane rozwiązania zacząć generować identyfikatory zaczynające od 0 lub 1. Klasa View ma inną instancję generatora, a także zaczyna odliczanie od numeru pierwszego, co spowoduje, że zarówno twój, jak i generator View'a wygeneruje te same identyfikatory, a w efekcie uzyskasz różne Widoki o tych samych identyfikatorach w widoku hierarchia.Niestety nie jest to dobre rozwiązanie dla tego, ale jest to hack, który powinien być dobrze udokumentowane:
public class AndroidUtils {
/**
* Unique view id generator, like the one used in {@link View} class for view id generation.
* Since we can't access the generator within the {@link View} class before API 17, we create
* the same generator here. This creates a problem of two generator instances not knowing about
* each other, and we need to take care that one does not generate the id already generated by other one.
*
* We know that all integers higher than 16 777 215 are reserved for aapt-generated identifiers
* (source: {@link View#generateViewId()}, so we make sure to never generate a value that big.
* We also know that generator within the {@link View} class starts at 1.
* We set our generator to start counting at 15 000 000. This gives us enough space
* (15 000 000 - 16 777 215), while making sure that generated IDs are unique, unless View generates
* more than 15M IDs, which should never happen.
*/
private static final AtomicInteger viewIdGenerator = new AtomicInteger(15000000);
/**
* Generate a value suitable for use in {@link View#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() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return generateUniqueViewId();
} else {
return View.generateViewId();
}
}
private static int generateUniqueViewId() {
while (true) {
final int result = viewIdGenerator.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 (viewIdGenerator.compareAndSet(result, newValue)) {
return result;
}
}
}
}
Myślę, że najlepszym sposobem jest zachować licznika int i przyrost podczas dodawania widoku i ustawić, że jak id – ingsaurabh
Possible duplikat programu [Android: View.setID (int id) programowo - jak uniknąć konfliktów ID?] (http://stackoverflow.com/questions/1714297/android-view-setidint-id-programmatically-how-to-avoid- id-conflicts) –