使用国家/地区代码在Android中以编程方式更改语言

时间:2016-02-23 11:30:33

标签: android locale

我想将我的应用语言环境更改为pt_BR。我做了以下事情。

更改区域设置的代码:

Locale locale;
if (localeName.contains("_")) {
           String localNameArray[] = localeName.split("_");
           locale = new Locale(localNameArray[0], localNameArray[1]);
} else {
       locale = new Locale(localeName);
}

Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, null);

string localeName包含pt_BR。

创建一个名为values-pt-rBR的新文件夹,并在该文件夹中添加strings.xml文件。

但是,当我将应用程序的语言更改为葡萄牙语巴西语(pt_BR)时,更改并未得到反映。

我已经检查了以下链接,但无法在此处找到任何解决方案:

Change language programatically in Android with country

Setting application locale to pt_BR programmatically

1 个答案:

答案 0 :(得分:3)

字符串文件:values / string.xml和values-pt-rBr / string.xml

        setLocale(new Locale("en"));
        String eng = getString(R.string.hello_world);
        setLocale(new Locale("pt", "Br"));
        String bra = getString(R.string.hello_world);
        if (!eng.equals(bra)) {
            Log.i("locale_test", "it works!");
        }


public void setLocale(final Locale locale) {
    Resources res = getResources();
    DisplayMetrics dm = res.getDisplayMetrics();
    Locale.setDefault(locale);
    android.content.res.Configuration conf = res.getConfiguration();
    conf.locale = locale;
    res.updateConfiguration(conf, dm);
}

<强>更新: 从android N开始需要新的方法 创建ContextWrapper类并在您的activity的attachBaseContext(Context)方法中使用它

public class ContextWrapper extends android.content.ContextWrapper {

 public ContextWrapper(final Context base) {
    super(base);
 }

 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);
    } else {
        configuration.setLocale(newLocale);
        DisplayMetrics dm = res.getDisplayMetrics();
        res.updateConfiguration(configuration, dm);
    }
    configuration.setLayoutDirection(newLocale);
    context = context.createConfigurationContext(configuration);

    return new ContextWrapper(context);
 }

}

@Override protected void attachBaseContext(final Context newBase) {
    String savedLocale = LocaleUtils.getSavedLocale();
    if (isNotEmpty(savedLocale)) {
        Locale appLocale = new Locale(savedLocale);
        ContextWrapper wrapped = ContextWrapper.wrap(newBase, appLocale);
        SalonyFormatter.getInstance(wrapped).refreshResources(wrapped);
        super.attachBaseContext(wrapped);
    } else {
        super.attachBaseContext(newBase);
    }
}