2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > android多语言编码格式 在Android中使用国家/地区代码以编程方式更改语言

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

时间:2019-01-10 17:50:38

相关推荐

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

字符串文件: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类,并在您活动的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);

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。