Android - 动态设置自定义View的id - setId
说明:
动态给自定义view设置id
AndroidStudio会报错:
因为在sdk17(4.2.2)以上可以使用myView.setId(View.generateViewId())才行,为了兼容,里面的id必须使用静态int类型。
解决三种写法:
1、sdk17(4.2.2以上)
tv_leftBtn_title.setId(View.generateViewId());
2、兼容自己写Utils类:
IdUtils.java(常用在sdk里面)
/**
* id
* 兼容sdk17(4.2.2)以下
* Created by zst on 2016/12/5.
*/
public class IdiUtils {
private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
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;
}
}
}
}
调用
tv_leftBtn_title.setId(IdiUtils.generateViewId());
3、写再配置xml文件里
Ids.xml(常用在有布局的app里面)
<resources>
<item type="id" name="snack" />
</resources>
调用
newRadioButton.setId(R.id.snack);