DEV Community

Ayush Bansal
Ayush Bansal

Posted on

Press a key without actually pressing it

Story Before

So I had this feature to build where a user is (let's say) writing his tweet. And just below the EditText I have provided with two buttons which allow the user to enter a "#" and a "@".

Issue

An easy job right(that's what I thought), just use editText.append("@"/"#") and the required character will be appended to the end of the text .
Well that's where I came across an issue . If the user changes the cursor position manually and presses one of the buttons, still the "#" or "@" is added at end of the text (instead of at the cursor position )BAD UX

Solution

In comes the BaseInputConnection's sendKeyEvent method .

EditText editText;
BaseInputConnection inputConnection = new BaseInputConnection(editText, true);
inputConnection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_POUND));

It will give the desired result.

Top comments (0)