我想知道是否有任何方法可以在 Android
中设置 EditText
的虚拟键盘的默认语言?
每次我将注意力集中在我的 EditText
上时,它都会用我的母语而不是英语打开虚拟键盘。
我猜这与设备设置有关,但如果有一种方法可以在 Android
开发中对其进行编程,那就太棒了。
最佳答案
LocaleHelper
”是您所需要的全部解决方案。您只需在应用程序的主类上初始化语言环境。之后,您的所有语言更改都将持续存在。
在应用程序类中进行以下更改:
public class MainApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
LocaleHelper.onCreate(this, "en");
}
}
LocalHelper.java 将是:
public class LocaleHelper {
private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";
public static void onCreate(Context context) {
String lang = getPersistedData(context, Locale.getDefault().getLanguage());
setLocale(context, lang);
}
public static void onCreate(Context context, String defaultLanguage) {
String lang = getPersistedData(context, defaultLanguage);
setLocale(context, lang);
}
public static String getLanguage(Context context) {
return getPersistedData(context, Locale.getDefault().getLanguage());
}
public static void setLocale(Context context, String language) {
persist(context, language);
updateResources(context, language);
}
private static String getPersistedData(Context context, String defaultLanguage) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
}
private static void persist(Context context, String language) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(SELECTED_LANGUAGE, language);
editor.apply();
}
private static void updateResources(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.locale = locale;
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
}
详细说明请引用this链接。
希望对你有所帮助。
关于android - 如何为 EditText 的虚拟键盘设置默认语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36643006/