7

I'm trying to detect a soft keyboard backspace in an empty EditText view. I've searched Stack Overflow and also Google and ~20 similar questions, but none have a solution for detecting a backspace in an empty EditText.

All of the answers evolve around this blog article https://code.i-harness.com/en/q/4a914a which specifically notes in the end that this does not detect backspace on an empty EditText view.

Help is much appreciated.

0xCursor
  • 2,242
  • 4
  • 15
  • 33
tosi
  • 611
  • 9
  • 24

3 Answers3

6

Most reliable solution to detect any event or text change of an EditText is using TextWatcher but if EditText is already empty, you can not detect backspace/delete key event on all devices.

Please keep it in mind that it is not possible and hopefully you or any other will not waste your time.

Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104
0

Hopefully this might help. I tried to use this in my projects.

public class MTextWatcher implements TextWatcher, View.OnKeyListener {
private int prevLen;


public MTextWatcher(int prevLen) {
    this.prevLen = prevLen;
}

@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) {
    //do something if you need
    prevLen = s.toString().length();
}

@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_DEL && prevLen == 0){
        // here you can trap the delete key pressed on empty edit text
    }
    return false;
}

}

next you can attach this listener with edit text like this

MTextWatcher watcher = new MTextWatcher(edittext.getText().toString().length());
    edittext.addTextChangedListener(watcher);
    edittext.setOnKeyListener(watcher);
-1

You can detect if edittext is empty or not with this code:

EditText usernameEditText = (EditText) findViewById(R.id.editUsername);
sUsername = usernameEditText.getText().toString();
if (sUsername.matches("")) {
Toast.makeText(this, "You did not enter a username", Toast.LENGTH_SHORT).show();
return;}