Android 如何通过编程更改输入法?

Android 如何通过编程更改输入法?,android,android-input-method,Android,Android Input Method,我有一个根据语言变化改变键盘的要求 我做了一些研究,发现可以使用这些API来完成 InputMethodManager设置InputMethod(android.os.IBinder,java.lang.String) InputMethodService switchInputMethod(java.lang.String) 对于第一个API,我需要一个IBinder令牌,它可以通过调用 mInputMethodService.getWindow().getWindow().getAttrib

我有一个根据语言变化改变键盘的要求

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

  • InputMethodManager设置InputMethod(android.os.IBinder,java.lang.String)
  • InputMethodService switchInputMethod(java.lang.String)
  • 对于第一个API,我需要一个IBinder令牌,它可以通过调用

    mInputMethodService.getWindow().getWindow().getAttributes().token

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

    mInputMethodService.switchInputMethod(id)

    更改输入法

    真正的问题是如何获取对InputMethodService对象的引用。

    PS: 我不想使用InputMethodManager的showInputMethodPicker(),因为我想更改我的需求 它来自我现有的对话框,其中有一个语言列表


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

    成功

    我唯一能改变当前输入法的方法就是自定义它

    为了我的责任。问题如果我更改系统语言,我必须将键盘更改为中文 从我的自定义设置应用程序转换为中文

    下面讨论的方法用于定制的LatinIME应用程序

    每个IME都有一个扩展类的类。在这个类中,我们可以重写一个方法 打电话。每当配置更改时,即。 当您更改系统区域设置时,将调用它

    在这里,我们可以检查当前选择的区域设置是否受 是否为当前输入法。如果没有,那么我们可以通过调用方法加载其各自的IME

    要获取id,我们可以通过查询获得可用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();
                }
        }
    
    字符串pinyinId=”“;
    InputMethodManager InputMethodManager=(InputMethodManager)getApplicationContext()
    .getSystemService(输入方法服务);
    List inputMethodInfos=inputMethodManager.getInputMethodList();
    对于(InputMethodInfo InputMethodInfo:inputMethodInfos){
    如果(inputMethodInfo.getId()包含(“拼音”)){
    pinyinId=inputMethodInfo.getId();
    }
    }
    

    在获得id后,我们可以调用switchInputMethod(pinyinId),它将更改输入法。

    这是一个老问题,但我是在2019年从谷歌直接来到这里的。 我也面临同样的问题&以下是我的解决方案:

    注意:您需要将应用程序安装为系统应用程序或使用平台密钥签名。

  • 在AndroidManifest.xml中添加写安全设置权限:

    <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
    
    
    
  • 如果适用,请使用InputMethodService switchInputMethod(字符串inputMethodId)。示例:
    switchInputMethod(“com.google.android.inputmethod.latin/com.android.inputmethod.latin.LatinIME”)