应用 Android Studio 中的语言未更改

Language not changing in app Android Studio

所以基本上我有一个微调器可以在三种语言之间进行选择,这是代码,我的语言确实发生了变化,但它似乎正在加载语言而不是我为其设置的资源。

我的代码

private void setLocale(String localeName){
            if (localeName.equalsIgnoreCase(""))
                return;
            Resources resources = getResources();
            Locale locale = new Locale(localeName);
            Locale.setDefault(locale);
            android.content.res.Configuration config = new
                    android.content.res.Configuration();
            config.locale = locale;
            resources.updateConfiguration(config, resources.getDisplayMetrics());
            //restart base activity
            this.finish();
            this.startActivity(this.getIntent());
        }

一种语言strings.xml文件

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Tabibi</string>
    <string name="already_have_an_account">تمتلك حساب؟</string>
    <string name="join">إنشاء حساب</string>
    <string name="login">تسجيل الدخول</string>
    <string name="language">اللغة</string>
</resources>

创建一个应用程序 Class 将语言设置为所有 activity

public class Application extends android.app.Application {

    private static Application applicationInstance;

    public static synchronized Application getInstance() {
        return applicationInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        applicationInstance = this;
    }

    public void initAppLanguage(Context context) {
        LocaleUtils.initialize(context, LocaleUtils.getSelectedLanguageId());
    }

}

LocalteUtils Class用于设置共享首选项中选择的语言,默认设置英文

public class LocaleUtils {

    public static final String ENGLISH = "en";
    public static final String FRENCH = "fr";
    public static final String SPANISH = "es";


    public static void initialize(Context context, @LocaleDef String defaultLanguage) {
        setLocale(context, defaultLanguage);
    }

    public static boolean setLocale(Context context, @LocaleDef String language) {
        return updateResources(context, language);
    }

    private static boolean updateResources(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);
        Resources resources = context.getResources();
        Configuration configuration = resources.getConfiguration();
        context.createConfigurationContext(configuration);
        configuration.locale = locale;
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());

        return true;
    }

    @Retention(RetentionPolicy.SOURCE)
    @StringDef({ENGLISH, FRENCH, SPANISH})
    public @interface LocaleDef {
        String[] SUPPORTED_LOCALES = {ENGLISH, FRENCH, SPANISH};
    }


    private static SharedPreferences getDefaultSharedPreference(Context context) {
        if (PreferenceManager.getDefaultSharedPreferences(Application.getInstance().getApplicationContext()) != null)
            return PreferenceManager.getDefaultSharedPreferences(Application.getInstance().getApplicationContext());
        else
            return null;
    }

    public static void setSelectedLanguageId(String id){
        final SharedPreferences prefs = getDefaultSharedPreference(Application.getInstance().getApplicationContext());
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("app_language_id", id);
        editor.apply();
    }

    public static String getSelectedLanguageId(){
        return getDefaultSharedPreference(Application.getInstance().getApplicationContext())
                .getString("app_language_id", "en");
    }
}

单击微调器选择的语言只是将语言设置为共享首选项并像这样重新启动activity

LocaleUtils.setSelectedLanguageId("fr");
        Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
        startActivity(i);

最后使用应用程序实例将首选项语言设置为 MainActivity。

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Application.getInstance().initAppLanguage(this);
        setContentView(R.layout.activity_main);
}

在清单文件中添加应用程序

<application
        android:name=".Application"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="AllowBackup,GoogleAppIndexingWarning">
        <activity android:name=".Main2Activity"/>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

此代码在 android 派中也能正常工作。 快乐编码...

接受的答案对我有用。但是,为了更好的兼容性,我想更换行:

context.createConfigurationContext(configuration);

LocaleUtils 中使用下面的代码将使更改配置适用于更多 android 版本 (API 15)

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
    context.createConfigurationContext(configuration);
} else {          
    context.getResources().updateConfiguration(configuration, context.getResources().getDisplayMetrics());
}