您的位置:首页 > 移动开发 > Android开发

android 中使用View.setId(int id),如何避免id冲突呢?

2015-07-04 10:25 543 查看
在项目开发中,有时候项目开发过程会需要,我们在代码中使用for循环创建View对象,并且每个View都需要setId(int id),这时候如何

避免id不和xml中冲突呢?在stackoverflow的
http://stackoverflow.com/questions/1714297/android-view-setidint-id-programmatically-how-to-avoid-id-conflicts

看到这篇文章很好的解决了上述的问题。

根据View的doc描述:

The identifier does not have to be unique in this view's hierarchy. The identifier should be a
positive number.

每个View都必须有一个唯一的标识符,这个标识符是一个正整数。在上述的例子中可能会遇到重复id的情况。

在sdk17 以上使用myView.setId(View.generateViewId());
在低于17 的版本中我们需要自己去写一些方法,我们

可以看看View.java的内部实现。然后把这个方法抽取出来写到在即的Utils.java,具体实现如下:

private
static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);

/**

* 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 static int generateViewId() {

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;

}

}

}

ID大于0x00FFFFFF的已经在xml中定义到了,容易发生冲突。

在调用的地方可以这样使用:

if
(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {

myView.setId(Utils.generateViewId());

} else {

myView.setId(View.generateViewId());

}

}

里边还提到了一些其他的方法,但是我在项目中是用的上述方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: