您的位置:首页 > 移动开发 > Android开发

Android 7.0以上版本,如何实现应用内语言切换

2018-03-15 10:50 1546 查看
7.0系统之前,系统语言的设置是一种;

7.0以后,系统语言的设置是一组;

所以,导致以前的设置语言的方法过时了,到了8.0就不能再起作用了。

原来的设置语言代码:



现在的需要区分版本设置:

public class MyContextWrapper extends android.content.ContextWrapper {

public MyContextWrapper(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);
context = context.createConfigurationContext(configuration);

} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

configuration.setLocale(newLocale);
context = context.createConfigurationContext(configuration);

}

return new ContextWrapper(context);
} }


接下来,只要重写BaseActivity的onAttachBaseContext方法:

@Override

protected void attachBaseContext(Context newBase) {

Locale newLocale;

// .. create or get your new Locale object here.

Context context = MyContextWrapper.wrap(newBase, newLocale);
super.attachBaseContext(context);
}


OK了,这样子就不会在7.0系统以上出现问题了。

参考自:https://www.jianshu.com/p/32ff13db1f0d
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: