如何使用 Strings.xml 更改文本值 - AndroidX

How to change text value using Strings.xml - AndroidX

我创建了体重指数应用程序,在该应用程序中,一些文字说,请输入您的身高

我使用 Strings.xml 设置它,在我的例子中,我希望能够将语言从文本 Please input your height 切换成另一种语言,任何解决方案?

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

你可以这样写一个方法:

@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();
}

您可以这样调用方法:

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);

string.xml 的好处是,如果您在 res 文件夹中创建一个新的文件夹值-"the language that you want",就像这个一样

是不是像这个例子一样,在我的案例中,应用程序的语言将根据手机上使用的语言将自己设置为英语或法语,你只需要有相同的字符串名称,你可以更改随心所欲的价值:)