要动态更改应用级资源的语言环境,你可以使用Android的多语言支持功能。下面是一个解决方法的代码示例:
LanguageManager
类,用于管理应用的语言环境:public class LanguageManager {
private static final String PREF_LANGUAGE = "language";
private static final String DEFAULT_LANGUAGE = "en";
public static void setLanguage(Context context, String language) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
preferences.edit().putString(PREF_LANGUAGE, language).apply();
}
public static String getLanguage(Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(PREF_LANGUAGE, DEFAULT_LANGUAGE);
}
}
LanguageActivity
类,用于让用户选择应用的语言环境:public class LanguageActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private String[] languages = {"English", "Chinese", "French"}; // 支持的语言列表
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_language);
ListView languageListView = findViewById(R.id.languageListView);
ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, languages);
languageListView.setAdapter(adapter);
languageListView.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
String language = ""; // 根据点击的位置确定选择的语言
switch (position) {
case 0: // English
language = "en";
break;
case 1: // Chinese
language = "zh";
break;
case 2: // French
language = "fr";
break;
}
LanguageManager.setLanguage(this, language);
recreate(); // 重新创建Activity以应用新的语言环境
}
}
MainActivity
的onCreate()
方法中,读取保存的语言环境并应用到应用程序:public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setLanguage(); // 设置语言环境
setContentView(R.layout.activity_main);
}
private void setLanguage() {
String language = LanguageManager.getLanguage(this);
Locale locale = new Locale(language);
Configuration config = getResources().getConfiguration();
config.setLocale(locale);
getResources().updateConfiguration(config, getResources().getDisplayMetrics());
}
}
这样,当用户在LanguageActivity
中选择了新的语言环境后,应用程序会重新创建MainActivity
,并应用新的语言环境。