Antony Sunggaki
Antony Sunggaki

Reputation: 191

How to change text value using Strings.xml - AndroidX

I Created Body Mass Index App, in that app, some text says, Please input your height etc.

I set it using Strings.xml, In my case, I want to be able to switch the language from the text Please input your height into another language, Any Solution?

Upvotes: 0

Views: 161

Answers (2)

Suryakant Bharti
Suryakant Bharti

Reputation: 701

First, create one Resources objects for each locale you need. Then, fetch the strings from the localized Resources object.

You can write a method like:

@NonNull Resources getLocalizedResources(Context context, Locale myLocale) {
    Configuration conf = context.getResources().getConfiguration();
    conf = new Configuration(conf);
    conf.setLocale(myLocale);
    Context localizedContext = context.createConfigurationContext(conf);
    return localizedContext.getResources();
}

You can call the method like:

Locale filipinoLocale = new Locale("fil");
Resources filipinoResource = getLocalizedResources(context, filipinoLocale);

Locale russianLocale = new Locale("ru");
Resources russianResource = getLocalizedResources(context, russianLocale);

Locale chineseLocale = new Locale("zh");
Resources chineseResource = getLocalizedResources(context, chineseLocale);

String filipinoString = filipinoResource.getString(R.string.mystring);
String russianString = russianResource.getString(R.string.mystring);
String chineseString = chineseResource.getString(R.string.mystring);

Upvotes: 1

Anthony Dodier
Anthony Dodier

Reputation: 31

the nice thing with string.xml is that if you create a new folder value-"the language that you want" like this one in your res folderenter image description here

Is that like in this exemple the language of the app is going to set itself to english or french in my case base on the language use on the cellphone you just need to have the same string name and you can change the value to wathever you want :)

enter image description here

enter image description here

Upvotes: 2

Related Questions