如何分配唯一的ID,以动态创建的意见? [英] How to assign unique ids to dynamically created Views?
问题描述
在我的应用程序,我创建浏览
- 在这种情况下,的EditText
- 动态。但是,每一个查看
我补充需要有一个唯一的ID。
In my app I am creating Views
- in this case an EditText
- dynamically. But every View
I add needs to have a unique id.
EditText editText = new EditText(context);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
editText.setLayoutParams(params);
// Which value am I supposed to use here?
editText.setId(value);
layout.addView(editText);
我害怕冲突,如果我给你一个随机值,我想不出任何方法来生成的ID不冲突的可能性。
I am afraid of conflicts if I assign a random value and I cannot think of any way to generate ids without the possibility of conflicts.
请注意,我知道,可以定义一组固定在RES /价值/ ids.xml的ID,但是这不是我想要的!我需要动态地创建IDS!我不知道我需要多少。
Please not that I know that one can define a fixed set of ids in res/values/ids.xml, but that is not what I want! I need to create the ids dynamically! I have no idea how many I need.
那么,有没有安全的方法来生成IDS?
So is there any safe way to generate ids?
推荐答案
- 手动设置
ID
s,使用someView.setId(
INT);
- 的
INT
必须是积极的,但另有arbitrary-它可以是任何你想要的(请继续阅读,如果这是可怕的。) - 的例如,如果要创建和编号若干意见重新presenting项目,你可以用他们的项目编号。的
Assign id
via code (programmatically)
- Manually set
id
s usingsomeView.setId(
int);
- The
int
must be positive, but is otherwise arbitrary- it can be whatever you want (keep reading if this is frightful.) - For example, if creating and numbering several views representing items, you could use their item number.
要分配ID - 的
To assign id -
for(int i =0 ; i < yourIDcount ; i++){
yourView.setId(i);
}
要获得ID - 的
To get id -
View.findViewById(yourView.getId());
此外,
API 17
推出 View.generateViewId()
生成一个唯一的ID。
API 17
introduced View.generateViewId()
which generates a unique ID.
检查:的
Check:
<一个href="http://stackoverflow.com/questions/8460680/how-can-i-assign-an-id-to-a-view-programmatically">how-can-i-assign-an-id-to-a-view-programmatically和<一href="http://stackoverflow.com/questions/10261190/android-assign-and-retrieve-ids-dynamically">android-assign-and-retrieve-ids-dynamically.
这篇关于如何分配唯一的ID,以动态创建的意见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!