一、切換系統語言APP崩潰的問題。
方法一、android:configChanges="locale|layoutDirection"
在清單文件中每個activity中添加該屬性,可以避免app處於后台時,切換了系統語言后,將app喚醒到前台時,應用崩潰的bug。
二、多語言。
提取出來的方法如下:
public static void qiChangeLauage(Context context,int type,boolean isrestart){
if (isrestart){
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
// 殺掉進程
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}else{
Resources resources = context.getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
Configuration config = resources.getConfiguration();
// 應用用戶選擇語言
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN_MR1){
config.setLocale(getSetLocale(type));//8.0以上使用
}else{
config.locale = getSetLocale(type);
}
resources.updateConfiguration(config, dm);//這個方法在8.0以后沒有效果,需要使用context.createConfigurationContext(configuration),具體使用方法在attachBaseContext中體現。
}
}
public static Locale getSetLocale(int type){
switch (type){
case 0:
return Locale.SIMPLIFIED_CHINESE;
case 1:
return Locale.TRADITIONAL_CHINESE;
case 2:
return Locale.ENGLISH;
default:
return Locale.SIMPLIFIED_CHINESE;
}
}
public static Context attachBaseContext(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 8.0需要使用createConfigurationContext處理
return updateResources(context);
} else {
return context;
}
}
@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context) {
Resources resources = context.getResources();
Locale locale = getSetLocale(MyApplication.getInstance().getLauageType());// getSetLocale方法是獲取新設置的語言
Configuration configuration = resources.getConfiguration();
configuration.setLocale(locale);
configuration.setLocales(new LocaleList(locale));
return context.createConfigurationContext(configuration);
}
具體使用:
1、在Application的oncreat方法中使用。設置多語言時,盡量使用getApplicationContext()。
2、在Application的以下方法中使用
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
*****.qiChangeLauage(this,getLauageType(),false);
}
這一步可要可不要,該方法的目的是獲取系統設置改變時,做出的相應的處理操作。這里的系統設置譬如:語言切換,屏幕旋轉等
3、語言切換的代碼,在高版本中廢棄了updateConfiguration方法,替代方法為createConfigurationContext,該方法是返回一個Context,也就是語言需要植入到Context中,每個Context都植入一遍。所以在BaseActivity中需要加入如下代碼
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(****.attachBaseContext(newBase));
}
這一步必須有,否則8.0以下的語言設置無效。