Android更改并在应用内设置默认语言环境

Xav*_*uza 20 java globalization android locale localization

我正在研究Android应用程序的全球化.我必须提供从应用程序中选择不同区域设置的选项.我在我的活动(HomeActivity)中使用以下代码,其中我提供了更改语言环境的选项

Configuration config = new Configuration();
config.locale = selectedLocale; // set accordingly 
// eg. if Hindi then selectedLocale = new Locale("hi");
Locale.setDefault(selectedLocale); // has no effect
Resources res = getApplicationContext().getResources();
res.updateConfiguration(config, res.getDisplayMetrics());
Run Code Online (Sandbox Code Playgroud)

只要没有像屏幕旋转那样的配置更改,其中locale默认为android系统级别语言环境而不是代码设置的语言环境,这样就可以正常工作.

Locale.setDefault(selectedLocale);
Run Code Online (Sandbox Code Playgroud)

我能想到的一个解决方案是使用SharedPreferences持久保存用户选择的语言环境,并且在每个活动的onCreate()方法中将语言环境设置为持久语言环境,因为onCreate()会在每次配置更改时反复调用.有没有更好的方法来做到这一点,所以我不必在每个活动中都这样做.

基本上我想要的是 - 一旦我在我的HomeActivity中更改/设置为某个区域设置,我希望我的应用程序中的所有活动都使用该区域设置本身而不管任何配置更改....除非并且直到将其更改为其他区域设置应用程序的HomeActivity提供更改区域设置的选项.

Mik*_*yer 26

虽然这个答案中说明的解决方案适用于一般情况,但我发现自己添加到我的偏好屏幕:

 <activity android:name="com.example.UserPreferences"
     android:screenOrientation="landscape"
     android:configChanges="orientation|keyboardHidden|screenSize">
 </activity>
Run Code Online (Sandbox Code Playgroud)

这是因为当应用程序处于横向模式并且首选项屏幕处于纵向模式时,更改区域设置并返回应用程序可能会导致问题.将两者设置为横向模式可防止这种情况发生.

一般解决方案

您需要在应用程序级别更改区域设置,以使其效果无处不在.

public class MyApplication extends Application
{
  @Override
  public void onCreate()
  {
    updateLanguage(this);
    super.onCreate();
  }

  public static void updateLanguage(Context ctx)
  {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
    String lang = prefs.getString("locale_override", "");
    updateLanguage(ctx, lang);
  }

  public static void updateLanguage(Context ctx, String lang)
  {
    Configuration cfg = new Configuration();
    if (!TextUtils.isEmpty(lang))
      cfg.locale = new Locale(lang);
    else
      cfg.locale = Locale.getDefault();

    ctx.getResources().updateConfiguration(cfg, null);
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在你的清单中你必须写:

<application android:name="com.example.MyApplication" ...>
  ...
</application>
Run Code Online (Sandbox Code Playgroud)

  • 请注意,不推荐使用 `updateConfiguration()`。[Set Locale programmatically](/sf/answers/3305644471/) 中建议了替代方案。 (2认同)