Set composing text on an EditText from a custom keyboard in Android

前端 未结 1 596
南方客
南方客 2021-01-21 15:59

Explanation of what I am trying to do

I\'m making a custom in-app keyboard that works on the same principle of this example. However, in my keyboard I\'m using popup w

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-21 16:20

    The following code sets a temporary composing span when the string in question is returned by the popup window

    if (selectedItem.equals("a")) {
        inputConnection.setComposingText("a", 1);
    }
    

    where selectedItem is the string chosen by the user from the key popup window candidates.

    Note that the a has an underline indicating that it is a composing span. (This is a contrived example from the question where a would be rendered as A if the text were committed immediately.)

    This also works for the real example in the question

    if (selectedItem.equals("\u1826\u180c")) {
        inputConnection.setComposingText("\u1826\u180c\u200d", 1);
    }
    

    Committing the composing span

    When it is confirmed that the user wants to keep the composing span (ie, they keep typing more letters in the word), it can be committed with

    inputConnection.commitText("\u1826\u180c", 1);
    

    Abandoning the composing span

    If the user clicks somewhere else, the composing span is not cancelled. But this is a different question.

    Your keyboard can override onUpdateSelection to listen for cursor changes there. Then call

    inputConnection.finishComposingText();
    

    to keep whatever text was in the composing region. Or

    ic.commitText("", 1);
    

    to get rid of it. See this answer for more.

    0 讨论(0)
提交回复
热议问题