如何在不重新创建活动的情况下更改Android App中的语言?

问题描述

不能在不重新创建活动的情况下更改语言环境
一个应用程序支持两种语言,当我更改语言时,我必须重新创建活动以显示期望的结果,但是我不想这样做。

private void setNewLocale(AppCompatActivity mContext,@LocaleManager.LocaleDef String language) {
        LocaleManager.setNewLocale(this,language);
        Intent intent = mContext.getIntent();
        startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));
    }

我也再次在“所有”文本字段上设置了文本,但这没有帮助!

当我参加应用程序的第三次活动时,如果我想返回第二个活动,则更改语言;如果我想在第二个活动和第一个活动中输入文本,那么我也必须重新创建那些我认为是不好的方法的活动去做吧。我只想更改语言,但不想重新创建活动!

单击按钮,我设置语言环境!

if(appPreference.getLanguage().equalsIgnoreCase("en")){
   setNewLocale(MainActivity.this,LocaleManager.araBIC);
}
else
    setNewLocale(MainActivity.this,LocaleManager.ENGLISH);

解决方法

首先在“活动”中定义这些功能

public void setLocale(String lang) {

        Locale myLocale = new Locale(lang);
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf,dm);
        Locale.setDefault(myLocale);
        onConfigurationChanged(conf);
    }

    private static void setLanguagePref(Context mContext,String localeKey) {
        AppPreference appPreference = new AppPreference(mContext);
        appPreference.setLanguage(localeKey);
    }

    public static String getLanguagePref(Context mContext) {
        AppPreference appPreference = new AppPreference(mContext);
        return appPreference.getLanguage();
    }

覆盖这些功能

@Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        //set Text Again of All layouts
        //Prefer to make a function and then set All Text

        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onResume() {

        setLocale(getLanguagePref(getApplicationContext()));
        super.onResume();
    }

现在在任何事件(如Onclick)上设置语言

   setLocale("ar");
   setLanguagePref(MainActivity.this,"ar");