Android change and set default locale within the app

前端 未结 1 1750
夕颜
夕颜 2021-02-02 11:27

I am working on globalization of Android app. I have to provide options to choose different locales from within the app. I am using the following code in my activity (HomeActivi

相关标签:
1条回答
  • 2021-02-02 11:52

    Although the solution stated in this answer works in the general case, I found myself adding to my preference screen:

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

    This is because when the application is in landscape mode and the preference screen in portrait mode, changing the locale and going back to the application might cause trouble. Setting both to be in landscape mode prevent this from happening.

    General solution

    You need to change the locale at the Application level, so that its effects are everywhere.

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

    Then in your manifest you have to write:

    <application android:name="com.example.MyApplication" ...>
      ...
    </application>
    
    0 讨论(0)
提交回复
热议问题