如何从android中的字符串数组中获取随机值?
问题描述:
在我的 values.xml 文件中,我有一个数组,就像这样;
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
还有这个
但是如何从 values.xml 文件中定义的列表中检索随机项目?
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)];
希望这会有所帮助.