I'm pretty new to Android, but a seasoned PHP dev, so some concepts I know how to do in PHP I'm struggling with in Android dev.
What I'm trying to do is use a string-array to define a textual pattern that I can swap out with a random value from another string array.
I know how to randomly choose an item from a string-array, so no problems there. But this is what I want to do:
<resources>
<string-array name="myPattern">
<item>myValues1</item>
<item>myValues1 of myValues2</item>
</string-array>
<s开发者_开发百科tring-array name="myValues1">
<item>string a</item>
<item>string b</item>
<item>string c</item>
<item>string d</item>
</string-array>
<string-array name="myValues2">
<item>string 1</item>
<item>string 2</item>
<item>string 3</item>
<item>string 4</item>
</string-array>
</resources>
The logic in my code is randomly choose a string from the pattern array. Then, swap out any instance of "myValues1" in that string with a random value from the string-array myValues1, and swap "myValues2" with a random item from myValues2 array.
Is this possible with arrays in Android, or should I be using some code to create the structures?
Thanks in advance.
Would this work for you?
class <yourActivity> extends Activity{
private final Random rand = new Random();
private String getRandom(int resourceId){
String [] vals = getResources().getStringArray(resourceId);
return vals[rand.nextInt(vals.length - 1)];
}
//your method somewhere...
void someMethod(){
swapOutMyValues1(getRandom(R.array.myValues1));
swapOutMyValues2(getRandom(R.array.myValues2));
}
}
Based on this page in the dev guide, you should be able to access the String arrays in your code like so:
Resources res = getResources();
String[] myValues1 = res.getStringArray(R.array.myValues1);
You'll want to do this in code because the resources you define in XML files are there to be used by the apps you write, so the idea is that you'll write code to make changes in some way.
精彩评论