监听语言变化
第一步:添加权限<!-- 语言改变权限-->
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION"/>
但是在4.2之后,需要同时设置layoutDirection,即android:configChanges="locale|layoutDirection"
上方就是三步监听语言变化的必经步骤。做完之后,就需要具体的处理逻辑了。
这个时候我们需要定义一个方法处理语言变化
@Override
public void onConfigurationChanged(Configuration newConfig) { // 监听语言的变化
super.onConfigurationChanged(newConfig);
initAppLanguage(getApplicationContext());
}
public void initAppLanguage(Context context) { //语言变化处理资源然后初始化fragment
if (context == null) {
return;
}
Configuration config = context.getResources().getConfiguration();
Locale locale = Locale.getDefault();
String language = locale.getLanguage();
if (language.equals("zh")) {
config.locale = Locale.SIMPLIFIED_CHINESE;
} else {
config.locale = Locale.ENGLISH;
}
context.getResources().updateConfiguration(config
, context.getResources().getDisplayMetrics());
initFragments();//再次初始化fragment 也就是再次的new新的fragment
//在这里让activity加载一次当前页面的fragment。
}
这样通过再次的加载就实现了App内的语言监听变化。