Android examples for User Interface:View Id
generate View Id for API level < 17
/*//w ww . j a v a 2 s . co 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 android.os.Build; import android.view.View; import java.util.concurrent.atomic.AtomicInteger; public class Main { private static final AtomicInteger sNextGeneratedId = new AtomicInteger( 1); /** * While {@link View#generateViewId()} require API Level >= 17, this tool is compatibe with all API. * * According to current API Level, it decide weather using system API or not. So you can use {@link * #generateViewId()} and {@link View#generateViewId()} in the * same time and don't worry about getting same id. * * @return Id */ public static int generateViewId() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { return generateCompatViewId(); } else { return View.generateViewId(); } } /** * 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 */ private 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; } } } }