1.創(chuàng)建多語言包
2.首先在onCreate方法中調(diào)用此方法查看上一次保存的是什么語言
public void setLanguage() {
//根據(jù)讀取到存放在sp里面的數(shù)據(jù) 進(jìn)行設(shè)置
Configuration configuration = getResources().getConfiguration();
SharedPreferences sharedPreferences = getSharedPreferences("key", MODE_PRIVATE);
int language = sharedPreferences.getInt("language", 0);
switch (language) {
case 0:
configuration.setLocale(Locale.CHINESE);
break;
case 1:
configuration.setLocale(Locale.ENGLISH);
break;
}
getResources().updateConfiguration(configuration, getResources().getDisplayMetrics());
}
3.點(diǎn)擊某個(gè)按鈕彈出選擇框選擇語言包
btn_qiehuan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String[] strings = {"簡體中文", "English"};
//首次進(jìn)入判斷是否是中文語言
int selected = getSharedPreferences("language", Context.MODE_PRIVATE).getInt("language", -1);
if (selected == -1) {
String defaultLanguage = Locale.getDefault().toString();
if (defaultLanguage.equals(Locale.CHINESE.toString()) || defaultLanguage.equals(Locale.SIMPLIFIED_CHINESE.toString())
|| defaultLanguage.equals(Locale.TRADITIONAL_CHINESE.toString())) {
selected = 0;
} else {
selected = 1;
}
}
new AlertDialog.Builder(MainActivity.this)
.setSingleChoiceItems(strings, selected,
new DialogInterface.OnClickListener() {
//點(diǎn)擊單選框某一項(xiàng)以后
public void onClick(DialogInterface dialogInterface, int i) {
SharedPreferences preferences = getSharedPreferences("language", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("language", i);
editor.commit();
dialogInterface.dismiss();
//重啟activity
finish();
Intent intent = new Intent(MainActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
})
.create()
.show();
}
});
效果演示~~~
8CAE7CF01EBF6D296AC192C82287105F.gif
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者