Search code examples
androidandroid-edittextkeyboard

How to get (or make) a reference to the InputConnection of an Android EditText


I am making a custom keyboard that I want to include in an app. I already know how to make a system keyboard. I don't want to do that because it requires installing by the user.

Whenever the user presses a key on the keyboard it should send the key text to whichever EditText currently has focus (if any).

The documentation states

An editor needs to interact with the IME, receiving commands through this InputConnection interface, and sending commands through InputMethodManager.

This is illustrated in the following image (where View is an EditText).

enter image description here

This makes it sound like I should be using an input connection to communicate with the EditText. So my question is, how does my custom keyboard view get a reference to the currently focused EditText's input connection. Or how does it start that connection?

Related


Solution

  • As @pskink mentioned in the comments, you can use

    InputConnection ic = editText.onCreateInputConnection(new EditorInfo());
    

    to get a reference to an EditText's input connection.

    It can be handed off to a custom keyboard when the EditText receives focus by adding a listener.

    // get the input connection from the currently focused edit text
    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                InputConnection ic = editText.onCreateInputConnection(new EditorInfo());
                keyboard.setInputConnection(ic); // custom keyboard method
            }
        }
    });