簡體   English   中英

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 ,當系統由於旋轉而重新創建活動時,請重新加載保存的語言環境值。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM