在IME和Android输入法之间进行切换

来源:互联网 发布:windows启动过程图解 编辑:程序博客网 时间:2024/05/19 18:16
 public void switchInputMethod(Activity myActivity,EditText inputText){
try
{
    //Get list of input methods
    List<InputMethodInfo> InputMethods=((InputMethodManager)myActivity.getSystemService(Context.INPUT_METHOD_SERVICE)).getEnabledInputMethodList();

    String nameIME = InputMethods.get(3).getServiceName();
    Log.i("Demo Error", "SWITCHING TO: "+nameIME);
    String NewInputMethodName=InputMethods.get(3).getId(); //Pick the first input method to switch to
    Log.i("Demo Error", "SWITCHING TO: "+NewInputMethodName);
    String curInputMethodId = Settings.Secure.getString(myActivity
        .getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
     Log.i("Demo Error", "CURRENT IME: "+curInputMethodId);

    // Solution 1 (X)
    // switchInputMethod is a method of android.inputmethodservice.InputMethodService
//     switchInputMethod(NewInputMethodName); //This throws an error

    // Solution 2 (OK)
    Settings.Secure.putString(myActivity.getContentResolver(),
    Settings.Secure.DEFAULT_INPUT_METHOD, NewInputMethodName);

    // Solution 3 (OK)
    if (myActivity.checkCallingOrSelfPermission(
        android.Manifest.permission.WRITE_SECURE_SETTINGS)
                        != 0) {
                    // PERMISSION_GRANTED == 0
            Log.i("Demo Error", "myActivity requires permission "
                + android.Manifest.permission.WRITE_SECURE_SETTINGS);
    }

    ((InputMethodManager)myActivity.getSystemService(Context.INPUT_METHOD_SERVICE))
        .setInputMethod(null, NewInputMethodName);
                

    // Show SoftInput Keyboard
    ((InputMethodManager)myActivity.getSystemService(Context.INPUT_METHOD_SERVICE))
        .showSoftInput(inputText, 0);

} catch(Exception e) {
    Log.i("Demo Error", e.getMessage());
}
原创粉丝点击