Android - 动态更改语言

时间:2015-05-05 12:13:04

标签: android locale dynamic-languages android-configchanges

在我的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"

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

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

您可以在回调onSaveInstanceState中保存语言配置,当系统因轮换而重新创建您的活动时,请重新加载已保存的区域设置值。

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

答案 1 :(得分:0)

您是否尝试在偏好设置中存储您的区域设置?例如:

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