android - 如何为 EditText 的虚拟键盘设置默认语言

标签 android android-studio android-edittext android-virtual-keyboard

我想知道是否有任何方法可以在 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/

相关文章:

java - 如何从 ListView 中引用元素内的 View ?

android - 在 android 中使用 restful web 服务处理身份验证

android - 尝试捕捉 : Is it OK to leave applications with handled exceptions?

Android:ListView 中的许多 Edittexts

android - 如何使用 EditText android 更改 TextInputLayout 中标签的字体样式

android - 从我的应用程序接听来电

android - JacksonParser 数据绑定(bind)和核心原因 "Found duplicate file for APK"?

android-studio - 错误 :Failed to resolve: com. github.bumptech.glide :glide:4. 0.0-SNAPSHOT

android - Gradle 同步失败,cmake "cause: executing external native build for cmake"

Android Studio 想要访问麦克风