Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 289
Anh-Tuan Mai Avatar asked Jan 08 '23 09:01

Anh-Tuan Mai


2 Answers

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());
like image 131
Maxime Epain Avatar answered Apr 27 '23 12:04

Maxime Epain


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)?

like image 45
Sir4ur0n Avatar answered Apr 27 '23 11:04

Sir4ur0n