【问题标题】:Can you programmatically switch between xml resource files on android?你能以编程方式在android上的xml资源文件之间切换吗?
【发布时间】:2013-09-03 00:03:12
【问题描述】:

Android 内置了基于用户设备语言 (http://developer.android.com/training/basics/supporting-devices/languages.html) 在资源之间切换的功能,但是否可以手动切换资源?

例如,如果我有: y项目/ 资源/ 价值观/ 字符串.xml 价值观-es/ 字符串.xml 价值观-fr/ 字符串.xml

我可以根据用户的偏好而不是他们的设备语言来更改使用哪个字符串文件吗?所以使用法语设备的人可以根据需要选择使用英文文本吗?

我知道我可以在代码中使用字符串变量而不是使用 xml,但我觉得 xml 会更整洁。

【问题讨论】:

    标签: android xml string resources


    【解决方案1】:

    是的,你可以。这是一个项目的复制/粘贴,根据用户偏好,放入onCreate():

    Resources res = getResources();
    Configuration conf = res.getConfiguration();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    
    String def = Locale.getDefault().getDisplayLanguage();
    String lang = prefs.getString("LANGUAGE", def);
    conf.locale = new Locale(lang);
    Log.v("myapp", lang+" = "+conf.locale+" = "+conf.locale.getDisplayName());
    res.updateConfiguration(conf, res.getDisplayMetrics());
    

    通过将名为 LANGUAGE 的用户首选项设置为所需语言的两个字母代码,然后重新启动 Activity,您可以手动覆盖设置语言。通过删除首选项,您将获得系统默认值。

    【讨论】:

      猜你喜欢
      • 2020-07-09
      • 1970-01-01
      • 1970-01-01
      • 2012-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多