Generate a value suitable for use in View #setId(int) . - Android User Interface

Android examples for User Interface:View Id

Description

Generate a value suitable for use in View #setId(int) .

Demo Code


//package com.java2s;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    /**//w  ww  . j  a  v  a  2s. co m
     * 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 final static int generateViewId() {
        AtomicInteger nextGeneratedID = new AtomicInteger(1);

        while (true) {
            int result = nextGeneratedID.get();

            int value = result + 1;

            if (value > 0x00FFFFFF) {
                value = 1;
            }

            if (nextGeneratedID.compareAndSet(result, value)) {
                return result;
            }
        }
    }
}

Related Tutorials