我尝试在我的应用程序中使用两种语言。我的项目中有不同的string.xml文件。 我试着像这样改变语言
like
我在按钮onClick
中使用我的课程public class LocaleManager {
public static final String LANGUAGE_ENGLISH = "en";
public static final String LANGUAGE_GEORGIAN = "ka";
private static final String LANGUAGE_KEY = "language_key";
public static Context setLocale(Context c) {
return updateResources(c, getLanguage(c));
}
public static Context setNewLocale(Context c, String language) {
persistLanguage(c, language);
return updateResources(c, language);
}
public static String getLanguage(Context c) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
return prefs.getString(LANGUAGE_KEY, LANGUAGE_ENGLISH);
}
@SuppressLint("ApplySharedPref")
private static void persistLanguage(Context c, String language) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
prefs.edit().putString(LANGUAGE_KEY, language).commit();
}
private static Context updateResources(Context context, String language) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.setLocale(new Locale(language));
context.getApplicationContext().createConfigurationContext(configuration);
} else {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration config = context.getResources().getConfiguration();
config.locale = locale;
context.getResources().updateConfiguration(config,
context.getResources().getDisplayMetrics());
}
return context;
}
public static Locale getLocale(Resources res) {
Configuration config = res.getConfiguration();
return Build.VERSION.SDK_INT >= 24 ? config.getLocales().get(0) : config.locale;
}
我有两个问题:
1)我测试了它并且语言环境正在成功更改,但我无法更改 flagImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!LocaleManager.getLanguage(LauncherActivity.this).equals(LocaleManager.LANGUAGE_ENGLISH))
LocaleManager.setNewLocale(LauncherActivity.this, LocaleManager.LANGUAGE_ENGLISH);
else
LocaleManager.setNewLocale(LauncherActivity.this, LocaleManager.LANGUAGE_GEORGIAN);
Intent i = new Intent(LauncherActivity.this, LauncherActivity.class);
startActivity(i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));
overridePendingTransition(R.anim.fade_in_dialog, R.anim.fade_out_dialog);
}
});
。是否可以在不刷新setText
的情况下更改setText
?
2)语言环境发生变化后,我尝试在activity
方法中使用我的setText
,但仍然无法更改
我如何解决这个问题?