Reputation: 1292
It is a real silly questions but I can't get it to work. I've used the search option, but couldn't not find my answer for android.
What I would like to do it the following:
In res/strings.xml i've got several strings
<string name="good0">blablabla</string>
<string name="good1">balablabla2</string>
etc
I want to show those strings randomly in a those when something happens:
Toast.makeText(this,R.string.good+(Math.random()*10), Toast.LENGTH_LONG).show();
But this doesn't work.
Thanks a lot for your help!
Upvotes: 2
Views: 6802
Reputation: 10633
If you have multiple string values or integer values and you to store it in a single string then String Builder is the best for this type of operation, For Example you have a string array and you want to store in a single string and then display this string then use this method. it will work hundred percent and it is too much suitable for this type of problems.**
String my_str=null;
StringBuilder bldr=new StringBuilder();
for(int j=0;j<5;j++)
bldr.append(phonearray[j]).append(",");
my_str=bldr.toString();
here in this case i am assigning phone array to a single string and then i will display it etc...
Upvotes: 0
Reputation: 13960
Use a String Array
.
In strings.xml
:
<resources>
<string-array name="messages">
<item>blablabla</item>
<item>blablabla</item>
</string-array>
</resources>
Then, in code you will have something like:
String[] messages = getResources().getStringArray(R.array.messages);
Random r = new Random();
String message = messages[r.nextInt(messages.length)];
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
Upvotes: 4
Reputation: 191048
You can't do that.
You will have to use a switch
block.
String myString;
switch(Math.random() * 10) {
case 0:
myString = getString(R.string.good1);
break;
}
Toast.makeText(this, myString, Toast.LENGTH_LONG).show();
Upvotes: 2
Reputation: 7351
R.string.good
is an int
because it refers to a Resource. This int IDENTIFIES a string in an XML file. Android provides a getString()
for its resource identifiers.
Android Docs on String Resources
You'll have to get the String out of the resource file this way, then concatenate as normal.
Upvotes: 2