Android:以编程方式切换到其他IME

184*_*615 11 android ime

http://developer.android.com/guide/topics/text/creating-input-method.html#GeneralDesign上 写着:

由于可以在设备上安装多个IME,因此为用户提供了一种直接从输入法UI切换到不同IME的方法.

假设我有两个输入方法的源,可以修改它.我想让用户快速切换它们,并准备为此保留一个按钮.如何"直接从输入法UI切换到不同的IME"?

184*_*615 15

从当前输入法切换到上一个输入法是:

//final String LATIN = "com.android.inputmethod.latin/.LatinIME";
// 'this' is an InputMethodService
try {
    InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
    final IBinder token = this.getWindow().getWindow().getAttributes().token;
    //imm.setInputMethod(token, LATIN);
    imm.switchToLastInputMethod(token);
} catch (Throwable t) { // java.lang.NoSuchMethodError if API_level<11
    Log.e(TAG,"cannot set the previous input method:");
    t.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

如果要切换到您知道其ID的特定输入法,您可以按照注释掉的行建议.

编辑@pRaNaY .getWindow()在静音编辑中建议单个(单击下面的"编辑"以查看历史记录).我记得它不适用于Android 2.3; 如果您查阅文档,您将看到第一个调用,InputMethodService.getWindow()返回一个Dialog(它不是子类Window),第二个调用Dialog.getWindow()返回一个Window.没有Dialog.getAttributes(),所以单一.getWindow()它甚至不会编译.


Rag*_*ood 11

出于安全原因,您无法通过代码更改用户当前活动的IME,抱歉.

但是,您可以显示系统提供的对话框,以允许用户选择其他已启用的对话框.

InputMethodManager imeManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); 
if (imeManager != null) {
    imeManager.showInputMethodPicker();
} else {
    Toast.makeText(context ,"Error", Toast.LENGTH_LONG).show();
}
Run Code Online (Sandbox Code Playgroud)