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

后端 未结 3 1113
忘掉有多难
忘掉有多难 2020-12-15 21:02

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


    Cow<         


        
相关标签:
3条回答
  • 2020-12-15 21:12
    String[] array = context.getResources().getStringArray(R.array.animals_array);
    String randomStr = array[new Random().nextInt(array.length)];
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-15 21:17
    String[] myArrayOfStrings = {"one", "two", "three" } 
    Random r = new Random();
    String myRandString = r.nextInt(myArrayOfStrings.length );
    
    0 讨论(0)
  • 2020-12-15 21:31

    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.

    0 讨论(0)
提交回复
热议问题