Created
September 18, 2017 22:30
-
-
Save pablisco/12ff1da415a1bc6c81038361391dec03 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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