Android - assign and retrieve ID's dynamically

女生的网名这么多〃 提交于 2019-12-24 17:53:23

问题


I know how to assing ID's dynamically by invoking setID(). For the ID's to be unique, I used to utilize ids.xml and pass to setID() ID's from the pre-generated pool of ID's.

Question 1: Is there any way to assign ID's without utilizing the ids.xml since I cannot anticipate how many ID's I will need in runtime?

I tried to bypass the first issue presented in Question 1 by dynamically assigning each of which an id based on its label's hash (each label is unique), but there is no way to gaurantee that ID's won't be colliding with ID's auto generated in R.java.

Question 1.1: How the ID naming collision can be resolved?

Question 2: Assume I have the ID value of which I assign and generate dynamically. Since the aformentioned ID does not appear in R.id, findViewById() won't be applicable for retrieving the view. Hence, how can the view be retrieved when the ID is known?

Answer 2: You'd be able to retrieve the view by its corresponding ID only after onCreate() has returned control (terminated).


回答1:


Is there any way to assign ID's without utilizing the ids.xml since I cannot anticipate how many ID's I will need in runtime?

This guarantees that every view has a unique ID

for(int i =0 ; i < yourIDcount ; i++){
yourView.setId(i);
}

how can the view be retrieved when the ID is known?

View.findViewById(yourView.getId());

can be used to get your view's id, since every view has a unique Id you can get back the view you wanted..

The word dynamic means which is created at runtime, since you assign id in onCreate it is assigned as the views id, since onCreate is called only once an activity is created, you can make sure that the id you assigned stays intact...




回答2:


From API level 17 you can get a new id by calling

View.generateViewId()

Details here.



来源:https://stackoverflow.com/questions/10261190/android-assign-and-retrieve-ids-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!