我如何在我的 Android 应用程序中以新更改的语言显示 toast 和标题。在我的代码中,一切正常。但我无法更新 toast 和标题的更改。 我的代码是:
- Changing the language in the application:
public void changeLang(String lang)
{
if (lang.equalsIgnoreCase(""))
return;
myLocale = new Locale(lang);
saveLocale(lang);
Locale.setDefault(myLocale);
android.content.res.Configuration config = new android.content.res.Configuration();
config.locale = myLocale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
updateTexts();
}
- Save the current locale:
public void saveLocale(String lang)
{
String langPref = "Language";
SharedPreferences prefs = getSharedPreferences("CommonPrefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(langPref, lang);
editor.commit();
}
- Loading a saved locale:
public void loadLocale()
{
String langPref = "Language";
SharedPreferences prefs = getSharedPreferences("CommonPrefs", Activity.MODE_PRIVATE);
String language = prefs.getString(langPref, "");
changeLang(language);
}
- Updating the UI elements of the current screen (you need to update only the screen in which a change of locale):
private void updateTexts()
{
setInterval.setText(R.string.btn_set_interval);
tv1.setText(R.string.tv_nodata);
tv2.setText(R.string.tv_nodata);
tv3.setText(R.string.tv_nodata);
tv4.setText(R.string.tv_nodata);
}
- Add events to the option menu.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
String lang = "en";
switch (item.getItemId()) {
case R.id.menu1:
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.cedesyn.com/"));
startActivity(browserIntent);
return true;
case R.id.submenu1:
lang = "en";
Toast.makeText(this,R.string.toast_lang_en, Toast.LENGTH_SHORT).show();
changeLang(lang);
return true;
case R.id.submenu2:
lang = "ru";
Toast.makeText(this,R.string.toast_lang_ru, Toast.LENGTH_SHORT).show();
changeLang(lang);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onConfigurationChanged(android.content.res.Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (myLocale != null){
newConfig.locale = myLocale;
Locale.setDefault(myLocale);
getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());
}
}
我可以通过 setText 更新按钮和 TextView 的语言,但我的问题是我将如何更新 toasts 的语言。 任何人都可以帮助我。
最佳答案
您应该将字符串导出到位于特定于该国家/地区的值文件夹中的 strings.xml。
您需要一个名为“values-XX”的文件夹,其中 XX 代表相关国家/地区的两个字母标识符(例如:values-es 或 values-fr)。在其中,您将把所有带有特定语言翻译的字符串放在一个新的 strings.xml 中。现在,在每个 strings.xml 文件中,为字符串指定相同的名称但具有不同的值(如 <string name="hello">Hello World</string>
和 <string name="hello">Bonjour</string>)
。
最后,您可以编写以下内容。
Toast.makeText(getApplicationContext(), getResources().getString(R.string.hello), Toast.LENGTH_LONG).show();
关于android - 我如何在 android 中以新更改的语言显示 toast 和标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31311572/