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

Android examples for User Interface:View Property

Description

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

Demo Code

/*/* w  w w.  ja  v  a 2 s  . c  o  m*/
 * Copyright (C) 2015 David Pizarro
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;

import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(
            1);

    /**
     * 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
     */
     static int generateCompatViewId() {
        for (;;) {
            final int result = sNextGeneratedId.get();
            int newValue = result + 1;
            /**
             * ID number larger than 0x00FFFFFF is reserved for static views defined in the /res xml files.
             * Android doesn't want you to use 0 as a view's id, and it needs to be flipped before 0x01000000 to avoid
             * the conflicts with static resource IDs
             */
            if (newValue > 0x00FFFFFF) {
                newValue = 1; // Roll over to 1, not 0.
            }
            if (sNextGeneratedId.compareAndSet(result, newValue)) {
                return result;
            }
        }
    }
}

Related Tutorials