Paramone
Paramone

Reputation: 2724

Use strings.xml values inside .Java Activities

So I'm going to make my application Multilingual and making different String.xml's for different languages. I'm also changing my texts, such as

String message = "Calling " + name;
                Context context = getApplicationContext();
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, message, duration);
                toast.show();

to

String message = toastCalling + name;

(From strings.xml)

<string name="toastCalling">Calling</string>

I'm facing a problem, that it apparently is an INT, and either cannot be resolved, or changes the value of toastCalling (Calling) to "278172" (Random Numbers)

Is there a way to get the ACTUAL value of R.String.toastCalling (Calling)

I have tried:

String whatever = getResources().getString(R.string.toastCalling);

But I don't think that's practical.

Thanks in advance!

Upvotes: 1

Views: 3260

Answers (1)

damian
damian

Reputation: 2011

If you're within the activity's scope, you can and are supposed to call getString(R.string.toastCalling); to receive the string. If you're not in the activity's scope, you need getResources, as in your example. This is how it is supposed to be done.

By the way, your three lines for the toast can be shortened into one: Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show();

Upvotes: 5

Related Questions