如何从一个字符串数组中的android一个随机值? [英] How to get a random value from a string array in android?

查看:1272
本文介绍了如何从一个字符串数组中的android一个随机值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

<一个href="http://stackoverflow.com/questions/2453989/help-in-getting-string-array-from-arrays-xml-file">Help在得到字符串数组从arrays.xml文件

<一个href="http://stackoverflow.com/questions/5034370/retreiving-an-item-from-arraylist-at-random">Retreiving从ArrayList的一个项目,在随机

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

解决方案

  String []数组= context.getResources()getStringArray(R.array.animals_array)。
字符串randomStr =数组[新的随机()nextInt(array.length)];
 

希望这有助于。

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.

这篇关于如何从一个字符串数组中的android一个随机值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆