Android 在应用内更改和设置默认区域设置

我正在研究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());

只要没有配置更改(如屏幕旋转),这就可以正常工作,其中区域设置默认为Android系统级区域设置,而不是代码设置的区域设置。

Locale.setDefault(selectedLocale);

我能想到的一个解决方案是使用共享首选项保留用户选择的区域设置,并在每个活动的onCreate()方法中将区域设置设置为持久化区域设置,因为onCreate()在每次配置更改时都会被一次又一次地调用。有没有更好的方法来做到这一点,这样我就不必在每一项活动中都这样做。

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


答案 1

尽管此答案中所述的解决方案在一般情况下有效,但我发现自己添加到了我的首选项屏幕:

 <activity android:name="com.example.UserPreferences"
     android:screenOrientation="landscape"
     android:configChanges="orientation|keyboardHidden|screenSize">
 </activity>

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

通用解决方案

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

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

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

<application android:name="com.example.MyApplication" ...>
  ...
</application>

答案 2

推荐