Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import android.os.Build
import android.view.View
import java.util.concurrent.atomic.AtomicInteger
object ViewCompanion {
private val NEXT_GENERATED_ID = AtomicInteger(1)
/**
* Inspired by: https://stackoverflow.com/a/15442997/458365
*/
fun generateViewId() : Int =
if (Build.VERSION.SDK_INT < 17) {
nextGeneratedId()
} else {
View.generateViewId()
}
private fun nextGeneratedId(): Int {
while (true) {
val result = NEXT_GENERATED_ID.get()
val newValue = result.getNextHighByteNonZero()
if (NEXT_GENERATED_ID.compareAndSet(result, newValue)) {
return result
}
}
}
}
/**
* aapt-generated IDs have the high byte nonzero; clamp to the range under that.
*/
private fun Int.getNextHighByteNonZero() = (this + 1).takeIf { it > 0x00FFFFFF } ?: 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment