开发者

Pick random strings from string.xml

I've just started out with android and write a simple dialog app with some random strings presented to the user. I started to think about best way to do that?

if strings.xml consist of strings like:

<string name="quote1">blaha blaha</string>
<string name="quote2">chit chat</string>

I guess there's a better way then generating a random int and then do

case 1:
   R.id.quote1

I guess it will end up with at least 50 different quotes in that file, tha开发者_如何学编程t's one ugly switch ..

Best regards


Try to get your quotes into a String array


If you cant use String Array then do this:

All .xml descriptor files in Android get compiled to your.package.R class.

You can use Java Reflection to inspect this class at runtime. In your case R.id is an inner static class.

Class clazz = R.id.class;
Field[] fields = clazz.getDeclaredFields();

// chose random field
int rnd = (int) (fields.length * Math.random());
String randomString = getString(fields[rnd].getInt(null));


Load your quotes into a list structure via xpath, select a random index from the list. Display that quote.

Alternately, get the count of quotes from the xml document, get a random index within that range, select the xml node at that index, and display it.


If you have only two strings its pretty simple, right. But if you have more, you might want to think about making a string array. You can make in XML easily.

Then just choose stringarray[random_number] as your string.


There's a way to select a random item from a sequential list without knowing the length of the list.

The algorithm is:

numItems = 0;
selectedItem = null;
while not end of list
{
  item = read item from list
  numItems = numItems+1;
  if (numItems == 1)
    selectedItem = item;
  else  if (random(numItems) == 0)
    selectedItem = item
}

The idea is that there is always a 1/numItems probability that the new item will replace the currently selected item.

For more information, see my article Random Selection from Large Groups. Scroll down to "What if I don't know how many there are?" The code is in C#, but the discussion is language agnostic.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜