Skip to content

Instantly share code, notes, and snippets.

@pablisco
Created September 18, 2017 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pablisco/12ff1da415a1bc6c81038361391dec03 to your computer and use it in GitHub Desktop.
Save pablisco/12ff1da415a1bc6c81038361391dec03 to your computer and use it in GitHub Desktop.
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