Android Studio应用中的语言未更改

gijlo24d  于 2022-11-03  发布在  Android
关注(0)|答案(3)|浏览(134)

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

我的代码

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>
tyky79it

tyky79it1#

创建一个为所有活动设置语言应用程序类

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类用于在共享首选项中设置选定的语言,并默认设置英语

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

单击微调器选择语言,将语言设置为共享首选项,然后像这样重新启动活动

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馅饼中也很好用。编码快乐...

o0lyfsai

o0lyfsai2#

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

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

polhcujo3#

如果您的应用程序工作文件处于开发模式,并且在发布此构建版本时未反映语言,则您希望添加这些行,以便更好地理解https://stackov12748481

android{
    bundle {
        language {
            enableSplit = false
        }
    }
}

相关问题