Android - 动态更改语言

Android - Dynamically change language

在我的 Android 应用程序中,我想动态更改默认语言。我已经实现了这个方法:

public void changeLanguage(String lang) {  //lang="it" or "en" for example
    myLocale = new Locale(lang);
    Resources res = getResources();
    DisplayMetrics dm = res.getDisplayMetrics();
    Configuration conf = res.getConfiguration();
    conf.locale = myLocale;
    res.updateConfiguration(conf, dm);
    Handler handler = new Handler();
    handler.postDelayed(new Runnable()
    {
        @Override
        public void run()
        {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
            {
                finish();
                startActivity(getIntent());
            } else recreate();
        }
    }, 1);
}

并且在清单中我将这一行添加到我的 MainActivity:

android:configChanges="locale|orientation"

我也试过这个:

android:configChanges="locale|layoutDirection"

此解决方案效果很好,但一旦屏幕旋转,就会恢复默认配置并恢复语言。

我该如何解决这个问题?

您可以在回调 onSaveInstanceState 中保存您的语言配置,当系统因旋转而重新创建您的 activity 时,重新加载保存的区域设置值。

private static final String LANG = "lang";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState != null) {
        Configuration configuration = getResources().getConfiguration();
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        configuration.locale = new Locale(savedInstanceState.getString(LANG));
        getResources().updateConfiguration(configuration, displayMetrics);
    }
}

/*
 * (non-Javadoc)
 * 
 * @see
 * android.support.v4.app.FragmentActivity#onSaveInstanceState(android.os
 * .Bundle)
 */
@Override
protected void onSaveInstanceState(Bundle outState) {
    // TODO Auto-generated method stub
    super.onSaveInstanceState(outState);

    outState.putString(LANG, "it");
}

您是否尝试过在首选项中存储您的语言环境?例如:

protected void onCreate(Bundle savedInstanceState) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    setLocale(prefs.getString("pref_locale", "en"));
}

public void changeLanguage(String lang) {
    prefs.setString("pref_locale", lang);
    setLocale(lang);
}

public void setLocale(String language_code) {
    Resources res = getResources();
    // Change locale settings in the app.
    DisplayMetrics dm = res.getDisplayMetrics();
    android.content.res.Configuration conf = res.getConfiguration();
    conf.locale = new Locale(language_code.toLowerCase());
    res.updateConfiguration(conf, dm);
}