Anh-Tuan Mai
Anh-Tuan Mai

Reputation: 1189

Android custom soft keyboard - how to clear edit text (commited text,...)

I'm following this example: https://android.googlesource.com/platform/development/+/master/samples/SoftKeyboard/

I'm having trouble while adding a clear text button. I want a button which clear in-focus text. But since I re-focus a not-empty text, I don't know how to delete existed characters. For example I have editText A and editText B.

focus A > commit "hello" > focus B > commit "world" > focus A > clear text in A >> FAIL

I still can delete text in A one by one character by using:

    //keyEventCode = KeyEvent.KEYCODE_DEL
    getCurrentInputConnection().sendKeyEvent(
            new KeyEvent(KeyEvent.ACTION_DOWN, keyEventCode));
    getCurrentInputConnection().sendKeyEvent(
            new KeyEvent(KeyEvent.ACTION_UP, keyEventCode));

But it's impossible to clear text A since text A length is unknown. In addition, KeyEvent.KEYCODE_CLEAR doesn't work with above function.

Any suggestion may help, thank you very much.

Upvotes: 5

Views: 3072

Answers (2)

Maxime Epain
Maxime Epain

Reputation: 381

I did something like this:

InputConnection inputConnection = getCurrentInputConnection();

CharSequence currentText = inputConnection.getExtractedText(new ExtractedTextRequest(), 0).text;
CharSequence beforCursorText = inputConnection.getTextBeforeCursor(currentText.length(), 0);
CharSequence afterCursorText = inputConnection.getTextAfterCursor(currentText.length(), 0);
inputConnection.deleteSurroundingText(beforCursorText.length(), afterCursorText.length());

Upvotes: 12

Sir4ur0n
Sir4ur0n

Reputation: 1823

How about you simply retrieve the view under focus using getCurrentFocus() (see documentation) and then call myFocusedEditText.setText("") (I assume your field is an EditText)?

Upvotes: 1

Related Questions