How do I change the input method programatically?

。_饼干妹妹 提交于 2019-12-03 08:46:59

Succeded!!!

The only way I have figured out of changing the current IME is by customizing it.

For my resp. problem I have to change the keyboard to chinese if I change the system language to chinese from my custom Settings application.

The approach discussed below was used for a custom LatinIME app.

Every IME has a class that extends InputMethodService class. In this class we can override a method called onInitializeInterface. This method gets called everytime when the configuration changes i.e. when you change your system Locale it will be called.

Here we can check whether the Locale that's currently been selected is supported by the current IME or not. If not then we can load its respective IME by calling the method switchInputMethod(id).

To get the id, we can query through inputMethodManager and get a list of available ids

    String pinyinId = "";

    InputMethodManager inputMethodManager = (InputMethodManager) getApplicationContext()
                    .getSystemService(INPUT_METHOD_SERVICE);
    List<InputMethodInfo> inputMethodInfos = inputMethodManager.getInputMethodList();

    for (InputMethodInfo inputMethodInfo : inputMethodInfos) {
            if (inputMethodInfo.getId().contains("pinyin")) {
                    pinyinId = inputMethodInfo.getId();
            }
    }

After getting the id we can call switchInputMethod(pinyinId) and it will change the IME.

This is an old question, but I was directed here from Google in 2019. I was facing the same problem & here is my solution:

NOTE: You need to install your app as system app OR signed with platform key.

  1. Add write secure setting permission in AndroidManifest.xml:

    <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
    
  2. Use InputMethodService switchInputMethod(String inputMethodId) where applicable. Example: switchInputMethod("com.google.android.inputmethod.latin/com.android.inputmethod.latin.LatinIME");

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!