How to commit composing text to an InputConnection when the user changes the selection

一曲冷凌霜 提交于 2019-12-11 07:33:07

问题


I am making a custom keyboard and have to set composing text before committing it. This is described in this Q&A.

I know how to commit text in general

inputConnection.commitText("text", 1);

But I don't know how to commit it if the user changes the cursor location by touching another part of the EditText. From observing other keyboards I know it is possible because they do it. But in my keyboard if I have

inputConnection.setComposingText("text", 1);

and then change the cursor position, the composing span is left. Any future changes will replace the composing span, not be entered at the new cursor position.

The post Android EditText listener for cursor position change gives some ideas for what you could do to an EditText, but inside the custom keyboard I don't have access to the EditText except for what the InputConnection gives me.

How do I handle know when the cursor/selection has moved?

I keep finding the answer to my question after I have started writing it. I will post the answer below.


回答1:


The editor (EditText, etc.) calls updateSelection on the InputMethodManager, which in turn notifies the onUpdateSelection listener. Thus, the keyboard can override onUpdateSelection and take care of the unfinished composing span there.

To handle an unfinished composing span you can use finishComposingText on the InputConnection. This will remove the composing span and commit whatever text was in the span.

Here is how it is implemented in the sample Android soft keyboard:

/**
 * Deal with the editor reporting movement of its cursor.
 */
@Override public void onUpdateSelection(int oldSelStart, int oldSelEnd,
        int newSelStart, int newSelEnd,
        int candidatesStart, int candidatesEnd) {
    super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd,
            candidatesStart, candidatesEnd);

    // If the current selection in the text view changes, we should
    // clear whatever candidate text we have.
    if (mComposing.length() > 0 && (newSelStart != candidatesEnd
            || newSelEnd != candidatesEnd)) {
        mComposing.setLength(0);
        updateCandidates();
        InputConnection ic = getCurrentInputConnection();
        if (ic != null) {
            ic.finishComposingText();
        }
    }
}


来源:https://stackoverflow.com/questions/45205410/how-to-commit-composing-text-to-an-inputconnection-when-the-user-changes-the-sel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!