选择Android应用的默认语言

时间:2018-08-27 14:26:15

标签: android localization

我正在开发仅包含捷克语内容的应用程序。如果我正确理解Android文档,则每个Android应用的默认语言均为英语。但这对我不起作用,因为我使用的是捷克语中具有不同语法规则的数量字符串,因此复数不能正常工作。我需要一种方法来强制将默认字符串资源的语言环境设置为cs进行修复。我知道我可以为捷克语言环境创建一个新的资源XML并在那里覆盖字符串,但是我想解决这个问题,因为那样我将在两个不同的资源文件中使用相同的字符串。 (这也会使复数形式在非捷克的设备上再次破损。)

谢谢您的建议。

2 个答案:

答案 0 :(得分:0)

 // Change locale settings in the app.
public static void setLocale(Context context, String languageCode) {
    Resources resources = context.getResources();
    DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
    android.content.res.Configuration configuration = resources.getConfiguration();
    configuration.locale = new Locale(languageCode.toLowerCase());
    resources.updateConfiguration(configuration, displayMetrics);
}

在任何地方调用该方法,例如:

setLocale(this, ENGLISH_CODE);

答案 1 :(得分:0)

我终于找到了解决方案,尽管它更像是一种解决方法。我在每个活动中使用了gunhansancarʼs LocaleHelper的一部分并覆盖了attachBaseContext()方法:

public class LocaleHelper {
    public static Context onAttach(Context context, String lang) {
        return setLocale(context, lang);
    }

    private static Context setLocale(Context context, String language) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return updateResources(context, language);
        }
        return updateResourcesLegacy(context, language);
    }

    @TargetApi(Build.VERSION_CODES.N)
    private static Context updateResources(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);
        Configuration configuration = context.getResources().getConfiguration();
        configuration.setLocale(locale);
        configuration.setLayoutDirection(locale);

        return context.createConfigurationContext(configuration);
    }

    @SuppressWarnings("deprecation")
    private static Context updateResourcesLegacy(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);
        Resources resources = context.getResources();
        Configuration configuration = resources.getConfiguration();
        configuration.locale = locale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLayoutDirection(locale);
        }
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        return context;
    }
}

public class MyActivity extends Activity {
    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(LocaleHelper.onAttach(newBase, "cs"));
    }
}

现在,我所有的捷克字符串和复数形式都保存在默认的strings.xml文件中,即使在非捷克设备上,复数形式也能正常工作。

相关问题