How to generate random events in android?

2019-07-16 19:42发布

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?

3条回答
迷人小祖宗
2楼-- · 2019-07-16 20:21

Is this something you are looking for?

Random r = new Random();
E element;
int rand = r.nextInt(array.length);
element = array[rand];
查看更多
爷、活的狠高调
3楼-- · 2019-07-16 20:41

I use java.util.random.

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

查看更多
放我归山
4楼-- · 2019-07-16 20:45

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);
查看更多
登录 后发表回答