如何从一个字符串数组中的android一个随机值?字符串、组中、android

2023-09-06 04:24:06 作者:鱼死海枯

在我values​​.xml文件中,我有一个数组,像这样;

<字符串数组名=动物阵列>     <项目>牛< /项目>     <项目>猪< /项目>     <项目>鸟< /项目>     <项目>羊< /项目> < /字符串数组>

在我的应用程序,我想其中一个值是随机的,但我不能确定如何做到这一点。我已经看过

Help在得到字符串数组从arrays.xml文件

Retreiving从ArrayList的一个项目,在随机

但我怎么检索我的名单是在values​​.xml文件中定义一个随机的项目?

解决方案

  String []数组= context.getResources()getStringArray(R.array.animals_array)。
字符串randomStr =数组[新的随机()nextInt(array.length)];
 
java中怎么判断一个字符串数组中包含某个字符或字符串

希望这有助于。

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

Retreiving an item from ArrayList at random

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

解决方案

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

Hope this helps.