如何在不重新创建 Activity 的情况下更改 Android 应用程序中的语言?

Ahm*_*ees 5 android locale setlocale

无法在不重新创建活动的情况下更改区域设置
应用程序支持两种语言,当我更改语言时,我必须重新创建活动才能显示所需的结果,但我不想这样做。

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));
    }
Run Code Online (Sandbox Code Playgroud)

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

当我处于应用程序的第三个活动时,当我回到第二个活动时,我更改语言,如果我愿意的话,第二个和第一个活动上的文本我也必须重新创建这些活动,我认为这是不好的方法。我只想更改语言,但不想重新创建活动!

单击按钮时,我设置了区域设置!

if(appPreference.getLanguage().equalsIgnoreCase("en")){
   setNewLocale(MainActivity.this, LocaleManager.ARABIC);
}
else
    setNewLocale(MainActivity.this, LocaleManager.ENGLISH);
Run Code Online (Sandbox Code Playgroud)

Ahm*_*ees 1

首先在您的 Activity 中定义这些函数

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

Run Code Online (Sandbox Code Playgroud)

覆盖这些函数

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

Run Code Online (Sandbox Code Playgroud)

现在设置任何事件的语言,例如 Onclick

   setLocale("ar");
   setLanguagePref(MainActivity.this, "ar");
Run Code Online (Sandbox Code Playgroud)