如何使用InputConnectionWrapper?

ubu*_*oid 9 android user-input input android-edittext

我有一个EditText.现在我想让用户对此进行所有更改EditText并使用它们,然后手动将它们插入到EditText.我不希望用户直接更改文本EditText.这应该只通过我的代码完成(例如使用replace()setText()).

我搜索了一下,发现了一个有趣的类名InputConnectionWrapper.根据javadoc,它应作为给定的代理InputConnection.所以我将其子类化为:

private class EditTextInputConnection extends InputConnectionWrapper {

    public EditTextInputConnection(InputConnection target, boolean mutable) {
        super(target, mutable);
    }

    @Override
    public boolean commitText(CharSequence text, int newCursorPosition) {
                    // some code which takes the input and manipulates it and calls editText.getText().replace() afterwards
        return true;
    }

}
Run Code Online (Sandbox Code Playgroud)

为了初始化包装器,我在EditText-subclass中覆盖了以下方法:

public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
    InputConnection con = super.onCreateInputConnection(outAttrs);
    EditTextInputConnection connectionWrapper = new EditTextInputConnection(con, true);
    return connectionWrapper;
}
Run Code Online (Sandbox Code Playgroud)

但是,commitText()永远不会被召唤.在onCreateInputConnection()被调用和构造EditTextInputConnection也,但从来没有commitText(),altough应该是,当我输入一些文字进入该领域.至少,这就是我理解其用法的方式InputConnectionWrapper.还是我错了?

编辑:看起来,commitText()只有".",""等特殊字符被调用.据我所知,InputConnectionWrapper.sendKeyEvent()应该调用所有其他字符的Android源代码,但事实并非如此......我绝对坚持这个点.我已经尝试过了EditText.onKeyPreIme(),但这只适用于硬件键盘.所以这是别无选择......我真的不明白,为什么Android会处理与硬件键盘不同的软键盘. EditText.onTextChanged()得到了非用户输入,所以这也不是,我正在寻找.

ubu*_*oid 5

原来,上述用法InputConnectionWrapper完全正确.但是,commitText()从未调用过(特殊情况除外),因为还有其他方法,在打字时使用.这些主要是setComposingText()sendKeyEvent().但是,覆盖很少使用的方法也很重要,deleteSurroundingText()或者commitText()确保捕获每个用户输入.