语言更改不会更改文本

时间:2019-01-04 11:25:14

标签: android android-layout

我有一个下拉菜单,用户可以选择EnglishSpanish语言。

问题在于更改语言后,它将日期,时间,进度对话框文本转换为西班牙语或英语,但我定义的字符串未转换为指定的语言。

尽管它们确实会在1或2次单击后进行转换,所以当我单击ES时,它不会将字符串更改为ES,但是随后我单击EN时,它将起作用并将所有字符串转换为ES,这不是理想的结果。

当用户点击任何一种语言时,我将执行以下代码。

languageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

 public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

        selectedLanguage=  getResources().getStringArray(R.array.language_array)[i];
        loadLanguage(selectedLanguage.toLowerCase());
 }

load language方法执行这些操作。

    public void loadLanguage(String language){

        String languageToLoad  = language;
        Locale locale = new Locale(languageToLoad);
        Locale.setDefault(locale);

        Configuration config = new Configuration();
        config.setLocale(locale);
        getBaseContext().getResources().updateConfiguration(config,
                getBaseContext().getResources().getDisplayMetrics());


        recreate(); 
 }

在每个活动中,我添加了以下代码。

  @Override
    protected void attachBaseContext(Context newBase) {
        Locale locale = new Locale(LanguagePreference.getInstance().getUserLanguage(newBase));
        Context context = ContextWrapper.wrap(newBase, locale);
        super.attachBaseContext(context);
    }

以下是我的Context Wrapper类。

  public static ContextWrapper wrap(Context context, Locale newLocale) {

        Resources res = context.getResources();
        Configuration configuration = res.getConfiguration();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            configuration.setLocale(newLocale);

            LocaleList localeList = new LocaleList(newLocale);
            LocaleList.setDefault(localeList);
            configuration.setLocales(localeList);

            context = context.createConfigurationContext(configuration);

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLocale(newLocale);
            context = context.createConfigurationContext(configuration);

        } else {
            configuration.locale = newLocale;
            res.updateConfiguration(configuration, res.getDisplayMetrics());
        }

        return new ContextWrapper(context);
    }}

0 个答案:

没有答案
相关问题