简体   繁体   中英

How to Generate IDs for Randomly Generated Buttons

I am generating a random number of buttons and need to set unique IDs for each one for further use. I am using View.generateViewID() to set the IDs, how can I get the IDs after though?

Instead, would it be possible to number the buttons by setting the ID to a variable, incrementing by 1 each time instead of generating random IDs somehow?

generateViewID() would return you an integer, guaranteed to be unique in the R class.

how can I get the IDs after though?

int generatedId = View.generateViewID();

Now you can set generatedID as the id of any view, and then get it back via view.getId() ;

Instead, would it be possible to number the buttons by setting the ID to a variable, incrementing by 1 each time instead of generating random IDs somehow?

Theoretically you could do that, and in most of cases you'd have no problems. But how sure you are you'll not collide with another id that is generated in R class? Do not make assumptions about the generated id types, today they are pretty huge number, maybe tomorrow the algorithm might change. Also, the framework provides you an API to generate ID, why would you disregard it? Adopt patterns, that the framework suggests you.

Apart from approach you are following there is another simple and concise approach. For dynamically added control(Button, Textview) you have have to maintain array/list of that control eg List<Button> lstButtons and to set id to that you have to pick/set on base id eg int buttonBaseId = 100; . For each dynamically added button you have to increase it by 1 eg buttonBaseId += 1; .

This approach can followed for multiple controls as well. Suppose you want to add TextView dynamically in that case you can choose Textview base id starting from 1000 and increasing it by 1 for each randomly added textview.

By following this approach you can retrieve any control from respective list at any point either by id or index.

In this way you are controlling where your button will start. Hope this will help you :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM