以下代码是切换语言按钮的事件函数,演示在中文和英文之间语言互换,这段代码主要是通过SharedPreference配置文件来读取当前的语言,并将切换后的值写入配置文件中:
private static final int LANGUAGE_ZH = 1;
private static final int LANGUAGE_EN = 2;
private void changeLanguage() {
SharedPreferences sp = getSharedPreferences("language", Context.MODE_PRIVATE);
int currentLanguage = sp.getInt("lan", LANGUAGE_ZH );
if (currentLanguage == LANGUAGE_EN) {
currentLanguage = LANGUAGE_ZH ;
} else {
currentLanguage = LANGUAGE_EN;
}
SharedPreferences.Editor editor = sp.edit();
editor.putInt("lan", currentLanguage);
editor.commit();
Refresh();
}
注意上面代码最后的Refresh()函数,该函数用来重新刷新界面,代码如下:
protected void Refresh() {
finish();
final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
APP启动页的onCreate()函数中代码如下。其主要功能为读取名为“language”的SharedPreference的值,并通过updateConfiguration函数切换界面显示语言,代码如下:
Locale myLocale;
SharedPreferences sp = getSharedPreferences("language", Context.MODE_PRIVATE);
int currentLanguage = sp.getInt("lan", LANGUAGE_ZH);
if (currentLanguage == LANGUAGE_ZH) {
//下面这行等同于 myLocale = Locale.CHINESE;
myLocale = new Locale("zh", "");
} else {
myLocale = Locale.ENGLISH;
}
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);