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?
A:
I use java.util.random.
It's basically plain java at this point. You can use java.util.nextInteger().
Unoti
2010-09-06 20:34:20
To clarify, that is `java.util.Random` and the `nextInt()` method.
CommonsWare
2010-09-06 20:36:42
A:
Is this something you are looking for?
Random r = new Random();
E element;
int rand = r.nextInt(array.length);
element = array[rand];
Marcus Johansson
2010-09-06 20:37:09
+4
A:
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);
Octavian Damiean
2010-09-06 20:37:21