Android轻松实现多语言的方法示例
时间:2023-02-26 08:35:54|栏目:Android代码|点击: 次
本文介绍了Android轻松实现多语言的方法示例,分享给大家,具体如下:
1.创建多语言包
2.首先在onCreate方法中调用此方法查看上一次保存的是什么语言
public void setLanguage() { //根据读取到存放在sp里面的数据 进行设置 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.点击某个按钮弹出选择框选择语言包
btn_qiehuan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String[] strings = {"简体中文", "English"}; //首次进入判断是否是中文语言 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() { //点击单选框某一项以后 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(); } });
效果演示~~~