如何以编程方式更改输入法?

use*_*555 3 android android-input-method

我需要根据语言的变化来更改键盘.

我做了一些研究,发现可以使用这些API完成

  1. InputMethodManager setInputMethod(android.os.IBinder,java.lang.String)
  2. InputMethodService switchInputMethod(java.lang.String)

对于第一个API,我需要一个IBinder令牌,可以通过调用从InputMethodService实例获取

mInputMethodService.getWindow().getWindow().的getAttributes().令牌

或者,如果我有对InputMethodService对象的引用,我可以简单地调用

mInputMethodService.switchInputMethod(ID)

更改输入法.

真正的问题是如何获得对InputMethodService对象的引用.

PS: 我不想使用InputMethodManager的showInputMethodPicker()因为我的要求我想从现有的具有语言列表的对话框中更改它.

我知道这对于用户应用程序是不可能的,但不确定它是否也不适用于系统应用程序.

use*_*555 5

Succeded!

我改变当前IME的唯一方法是通过自定义它.

对于我的resp.问题如果我从自定义设置应用程序将系统语言更改为中文,我必须将键盘更改为中文.

下面讨论的方法用于自定义LatinIME应用程序.

每个IME都有一个扩展InputMethodService类的类.在这个类中,我们可以覆盖一个名为onInitializeInterface的方法.每次配置更改时都会调用此方法,即当您更改系统区域设置时,它将被调用.

在这里,我们可以检查当前IME是否支持当前选择的Locale.如果没有,那么我们可以通过调用方法switchInputMethod(id)来加载它各自的IME .

要获取id,我们可以通过inputMethodManager查询并获取可用id列表

    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();
            }
    }
Run Code Online (Sandbox Code Playgroud)

获取id后我们可以调用switchInputMethod(pinyinId),它将改变IME.