程序化视图如何设置唯一 ID? [英] Programmatic Views how to set unique id's?
问题描述
我正在我的应用程序中创建一堆程序化的View
.看起来它们在默认情况下都具有相同的 id=-1
.为了与他们合作,我需要生成唯一的 ID.
I am creating in my app bunch of programmatic View
s. As it appeared to be they all by default have the same id=-1
. In order to work with them I need to generate unique id's.
我尝试了几种方法 - 随机数生成并基于当前时间,但无论如何不能 100% 保证不同的视图会有不同的 id
I have tried several approaches - random number generation and based on current time, but anyway there's no 100% guarantee that different Views will have different id's
只是想知道有没有更可靠的方法来生成独特的?可能有特殊的方法/类?
Just wondering is there any more reliable way to generate unique ones? Probably there's special method/class?
推荐答案
只是对@phantomlimb 的回答的补充,
Just an addition to the answer of @phantomlimb,
而 View.generateViewId()
需要 API 级别 >= 17,
此工具兼容所有 API.
while View.generateViewId()
require API Level >= 17,
this tool is compatibe with all API.
根据当前的 API 级别,
它使用系统 API 来决定天气.
according to current API Level,
it decide weather using system API or not.
所以你可以使用 ViewIdGenerator.generateViewId()
和 View.generateViewId()
同时,不用担心得到相同的id
so you can use ViewIdGenerator.generateViewId()
and View.generateViewId()
in the
same time and don't worry about getting same id
import java.util.concurrent.atomic.AtomicInteger;
import android.annotation.SuppressLint;
import android.os.Build;
import android.view.View;
/**
* {@link View#generateViewId()}要求API Level >= 17,而本工具类可兼容所有API Level
* <p>
* 自动判断当前API Level,并优先调用{@link View#generateViewId()},即使本工具类与{@link View#generateViewId()}
* 混用,也能保证生成的Id唯一
* <p>
* =============
* <p>
* while {@link View#generateViewId()} require API Level >= 17, this tool is compatibe with all API.
* <p>
* according to current API Level, it decide weather using system API or not.<br>
* so you can use {@link ViewIdGenerator#generateViewId()} and {@link View#generateViewId()} in the
* same time and don't worry about getting same id
*
* @author fantouchx@gmail.com
*/
public class ViewIdGenerator {
private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
@SuppressLint("NewApi")
public static int generateViewId() {
if (Build.VERSION.SDK_INT < 17) {
for (;;) {
final int result = sNextGeneratedId.get();
// aapt-generated IDs have the high byte nonzero; clamp to the range under that.
int newValue = result + 1;
if (newValue > 0x00FFFFFF)
newValue = 1; // Roll over to 1, not 0.
if (sNextGeneratedId.compareAndSet(result, newValue)) {
return result;
}
}
} else {
return View.generateViewId();
}
}
}
这篇关于程序化视图如何设置唯一 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!