How to get a random value from a string array in a

2019-01-24 04:20发布

问题:

In my values.xml file, I have an array, like this;

<string-array name="animals-array">
    <item>Cow</item>
    <item>Pig</item>
    <item>Bird</item>
    <item>Sheep</item>
</string-array>

In my app, I want to get one of these values at random, but I am unsure how to do this. I have looked at

Help in getting String Array from arrays.xml file

and this

Retrieving a random item from ArrayList

But how do I retrieve a random item from my list that is defined in the values.xml file?

回答1:

String[] array = context.getResources().getStringArray(R.array.animals_array);
String randomStr = array[new Random().nextInt(array.length)];

Hope this helps.



回答2:

1. Retrive the Complete String Array from the xml and put it inside an ArrayList using Arrays.asList() method.

2. Use Math.random()*mArr.size() function to get a random number. (mArr is the ArrayList)

3. Then use this random number to get an animal from the ArrayList like

   `myArr.get(myrand);`

4. The reason i suggested the use of ArrayList (ie Collection framework) cause that will give you more flexibility.



回答3:

String[] myArrayOfStrings = {"one", "two", "three" } 
Random r = new Random();
String myRandString = r.nextInt(myArrayOfStrings.length );