[ACCEPTED]-Detect delete button in soft keyboard-android-softkeyboard

Accepted answer
Score: 15

Possible duplicate of Android EditText delete(backspace) key event

just checked the code 14 from that question (which actually come 13 from the provided question and answered 12 by Labeeb P) with the test project with 11 just two edits on layout and it seems to 10 work just fine - I'm able to receive delete 9 even if edit is empty.

    final EditText edit1 = (EditText) findViewById(R.id.editText1);

    edit1.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // You can identify which key pressed buy checking keyCode value
            // with KeyEvent.KEYCODE_
            if (keyCode == KeyEvent.KEYCODE_DEL) {
                // this is for backspace
                Log.e("IME_TEST", "DEL KEY");
            }
            return false;
        }
    });

Seems android documentation 8 of EditText should be made more clear or 7 at least any guide for EditText - Soft Keyboard 6 interaction provided, because there many 5 typical ones whose should be worked out 4 by nearly every developer.

UPDATE: Seems this way 3 doesn't work on latest (at least after 4.1) Android 2 versions. This answer seems to work on versions after 1 4.1.

Score: 9

A simpler solution to this that I stumbled 16 upon is using an InputFilter. InputFilter's filter() method 15 appears to report all soft keyboard events 14 - even those where the EditText's value 13 isn't changing.

So to address your specific 12 situation, construct an input filter and 11 set accordingly:

private InputFilter filter = (charSequence, start, end, dest, dStart, dEnd) -> {

    if (end == 0 || dStart < dEnd) {
        // backspace was pressed! handle accordingly
    }

    return charSequence;
};

...

myEditText.setFilters(new InputFilter[] { filter });

Backspace events can be 10 evaluated using end, dStart, and dEnd. dStart will always be 9 less than dEnd if a character was deleted. If 8 the EditText is empty, you can still evaluate backspace 7 presses by checking if end == 0.

Note that bulk 6 deletes will also be caught in this if statement, so 5 you may want to do some extra checking withing 4 filter(). Also note that if you're using your computer 3 keyboard to type into EditTexts in emulators, you 2 can get unexpected results. Best to click 1 software buttons for testing.

Score: 4

Use the Extension provided at, https://github.com/ciasaboark/Android-Shell/blob/master/src/com/example/com/programmingthetux/tutorial/ZanyEditText.java

import java.util.Random;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputConnectionWrapper;
import android.widget.EditText;
/**
 * Created by mkallingal on 4/25/2016.
 */
public class CustomEditText extends EditText {

    private Random r = new Random();

    public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public CustomEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomEditText(Context context) {
        super(context);
    }

    public void setRandomBackgroundColor() {

    }

    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        return new ZanyInputConnection(super.onCreateInputConnection(outAttrs),
                true);
    }

    private class ZanyInputConnection extends InputConnectionWrapper {

        public ZanyInputConnection(InputConnection target, boolean mutable) {
            super(target, mutable);
        }

        @Override
        public boolean sendKeyEvent(KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN
                    && event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
                CustomEditText.this.setRandomBackgroundColor();
                // Un-comment if you wish to cancel the backspace:
                // return false;
            }
            return super.sendKeyEvent(event);
        }


        @Override
        public boolean deleteSurroundingText(int beforeLength, int afterLength) {
            // magic: in latest Android, deleteSurroundingText(1, 0) will be called for backspace
            if (beforeLength == 1 && afterLength == 0) {
                // backspace
                return sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
                        && sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL));
            }

            return super.deleteSurroundingText(beforeLength, afterLength);
        }

    }
}

Now you can 1 use it in your Activity like so:

final CustomEditText editText = new CustomEditText(cxt);

editText.setOnKeyListener(new View.OnKeyListener() {
                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_DEL) {
                            String _text= editText.getText().toString();
                            if(StringUtils.isBlank(_text))
                                 //editText is now empty
                            }
                        }
                        return false;
                    }
                });
Score: 1

I achieved it by overriding EditText in order to 5 get access to InputConnection object which contains deleteSurroundingText method. It 4 helps to detect deletion (backspace) event. Please, take 3 a look at a solution I provided there: Android - cannot capture backspace/delete press in soft. keyboard

This 2 solution works properly for both hardKeyboard 1 and softKeyboard.

Score: 0
package com.bikash.layout;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity implements View.OnKeyListener, TextWatcher {
    EditText otp1, otp2, otp3, otp4, otp5, otp6;
    private boolean canDelete = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        otp1 = findViewById(R.id.otp1);
        otp2 = findViewById(R.id.otp2);
        otp3 = findViewById(R.id.otp3);
        otp4 = findViewById(R.id.otp4);
        otp5 = findViewById(R.id.otp5);
        otp6 = findViewById(R.id.otp6);

        otp1.addTextChangedListener(this);
        otp2.addTextChangedListener(this);
        otp3.addTextChangedListener(this);
        otp4.addTextChangedListener(this);
        otp5.addTextChangedListener(this);
        otp6.addTextChangedListener(this);

        otp1.setOnKeyListener(this);
        otp2.setOnKeyListener(this);
        otp3.setOnKeyListener(this);
        otp4.setOnKeyListener(this);
        otp5.setOnKeyListener(this);
        otp6.setOnKeyListener(this);

        otp1.requestFocus();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (otp1.isFocused()) {
            if (otp1.getText().toString().length() == 1) {
                otp2.requestFocus();
            }
        }
        if (otp2.isFocused()) {
            if (otp2.getText().toString().length() == 1) {
                otp3.requestFocus();
            }
        }
        if (otp3.isFocused()) {
            if (otp3.getText().toString().length() == 1) {
                otp4.requestFocus();
            }
        }
        if (otp4.isFocused()) {
            if (otp4.getText().toString().length() == 1) {
                otp5.requestFocus();
            }
        }
        if (otp5.isFocused()) {
            if (otp5.getText().toString().length() == 1) {
                otp6.requestFocus();
            }
        }
        if (otp6.isFocused()) {
            if (otp6.getText().toString().length() == 1) {

            }
        }

    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {

        switch (v.getId()) {
            case R.id.otp2: {
                if (keyCode == KeyEvent.KEYCODE_DEL) {

                        otp1.setText("");
                        otp1.requestFocus();
                }
                break;
            }
            case R.id.otp3: {
                if (keyCode == KeyEvent.KEYCODE_DEL) {

                        otp2.setText("");
                        otp2.requestFocus();
                }
                break;
            }case R.id.otp4: {
                if (keyCode == KeyEvent.KEYCODE_DEL) {

                        otp3.setText("");
                        otp3.requestFocus();
                }
                break;
            }case R.id.otp5: {
                if (keyCode == KeyEvent.KEYCODE_DEL) {

                        otp4.setText("");
                        otp4.requestFocus();
                }
                break;
            }case R.id.otp6: {
                if (keyCode == KeyEvent.KEYCODE_DEL) {
                    
                        otp5.setText("");
                        otp5.requestFocus();
                }
                break;
            }
        }
        return false;
    }
}

0

More Related questions