我有一个ImageButton,当用户点击它时,EditText被添加到布局中。所以我想要的是每个EditText都有一个唯一的id。
a = 0;
imgAddText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (a <= 5) {
layoutAddText.addView(createEditText());
a++;
}
}
});
private EditText createEditText() {
final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
final EditText editText = new EditText(this);
return editText;
}
答案 0 :(得分:1)
actually all view have setId
method. You can make use of it.
setId(int id)
i would strong suggest you use setTag
instead. I hope reason being your setting id is using same id to get it back by findViewId(int)
. Same thing you can achieve by findViewWithTag(Object tag)
答案 1 :(得分:0)
In createEditText() method try this
EditText editText=(EditText)findViewById(R.id.edit);
editText.setLayoutParams(layoutParams);
editText.setId(R.id.edit);
return editText;
答案 2 :(得分:0)
您可以尝试将标记而不是ID设置为:
editText.setTag(UUID.randomUUID().toString());
或通过创建类似IdGenerator
的类来生成唯一ID:
public class IdGenerator() {
private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
public static int generateViewId() {
for (; ; ) {
final int result = sNextGeneratedId.get();
int newValue = result + 1;
if (newValue > 0x00FFFFFF) newValue = 1;
if (sNextGeneratedId.compareAndSet(result, newValue)) {
return result;
}
}
}
}
然后做:
editText.setId(IdGenerator.generateViewId());