How to generate random events in android?

馋奶兔 提交于 2019-12-24 00:47:44

问题


I have a an array of objects and would like to be able to randomly choose one from the list when a button is pressed. How would you do that in Android?


回答1:


Do something like this inside your onClickListener

Random rand = new Random();
int selector = rand.nextInt(yourList.length);
yourList.get(selector);

Something like that.

EDIT: Actually if it is an ArrayList then it will be more like this

Random rand = new Random();
int selector = rand.nextInt(yourList.size());
yourList.get(selector);



回答2:


I use java.util.random.

It's basically plain java at this point. You can use java.util.nextInteger().




回答3:


Is this something you are looking for?

Random r = new Random();
E element;
int rand = r.nextInt(array.length);
element = array[rand];


来源:https://stackoverflow.com/questions/3654130/how-to-generate-random-events-in-android

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