【问题标题】:How to change text value using Strings.xml - AndroidX如何使用 Strings.xml 更改文本值 - Android
【发布时间】:2020-02-08 02:57:39
【问题描述】:

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

我使用Strings.xml 设置它,就我而言,我希望能够将请输入您的身高文本中的语言切换为另一种语言,有什么解决方案吗?

【问题讨论】:

标签: java android string locale


【解决方案1】:

string.xml 的好处在于,如果您在 res 文件夹中创建一个新的文件夹值——“您想要的语言”,就像这个文件夹

就像在这个例子中一样,应用程序的语言是否会根据手机上使用的语言设置为英语或法语,您只需要具有相同的字符串名称,您可以将值更改为随便你:)

【讨论】:

    【解决方案2】:

    首先,为您需要的每个语言环境创建一个 Resources 对象。然后, 从本地化的 Resources 对象中获取字符串。

    您可以编写如下方法:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      • 2020-07-27
      • 2013-01-03
      相关资源
      最近更新 更多