Randomly select a string from strings.xml in Android

前端 未结 3 1942
慢半拍i
慢半拍i 2020-12-10 06:25

I need to randomly select a string defined within strings.xml file in android.

For example my strings.xml is :


    

        
3条回答
  •  长情又很酷
    2020-12-10 06:48

    The best way is you declare you Strings as an Array, then get it like this:

    String[] arrayOfStrings = context.getResources().getStringArray(R.array.your_string_array);
    String randomString = arrayOfStrings[new Random().nextInt(arrayOfStrings.length)];
    

    Then you can use it as you like.

提交回复
热议问题