A M
A M

Reputation: 849

Android - EditText delete (soft button) key event and deleting action

In my fragment, I want to intercept the event "delete (soft button) pressed" from the software keyboard, on an EditText.

I can do that, using the following code:

positionEditText.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
            if(keyCode == KeyEvent.KEYCODE_DEL) {
                Log.d("TAG", "OnKeyListener, premuto BACKSPACE");
                backspacePressed = true;
                return true;
            }
            return false;
        }
    });

The problem is that doing so, I can't properly delete the edit text. The deleting function only works if I press and hold the delete button.

Upvotes: 1

Views: 2548

Answers (2)

Paresh
Paresh

Reputation: 6857

if(keyCode == KeyEvent.KEYCODE_DEL) {
    Log.d("TAG", "OnKeyListener, premuto BACKSPACE");
    backspacePressed = true;
    return true; // This is the problem
}

By returning true, you are telling system that.. I'm going to handle that. Remove it and it will work.

Upvotes: 1

Cao Minh Vu
Cao Minh Vu

Reputation: 1950

Try this:

positionEditText.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
            if(keyCode == KeyEvent.KEYCODE_DEL) {
                Log.d("TAG", "OnKeyListener, premuto BACKSPACE");
                backspacePressed = true;
            }
            return false;
        }
    });

Upvotes: 1

Related Questions