Home > Net >  Detect delete key on empty input field for mobile devices?
Detect delete key on empty input field for mobile devices?

Time:10-08

Somehow the OnValueChanged() method doesn't get called when an user presses the delete key on an empty android mobile Inputfield.

I guess as it is empty the value of inputfield is "" before pressing delete and still "" after. Thus there isn't an OnValueChanged() called.

I tried checking for the delete key in Update() but Android doesn't seem to notify an application when the delete key gets pressed.

How can I check if the delete key is pressed?


What I want to achieve is that the Inputfield gets deactivated when the user presses the delete key and the inputfield is empty...


Using c# and Unity

CodePudding user response:

Unfortunately, I am not familiar with C languages, I work with Java and Kotlin. In Java development, the implementation of the solution would look like this:

editText.setOnKeyListener(new 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
        }
        return false;       
    }
});

Answer taken from this page: Android EditText delete(backspace) key event

I hope this helps you

CodePudding user response:

As getting an actual KeyEvent from Android for the delete key seems to be quite complicated, I managed to do an easy workaround.

Simply set the text of the Inputfield on activation to " " (Simply space). That way when the user presses the delete key, the space gets deleted and OnValueChanged gets called.

To avoid problems with the additional space in the input, you can simply implement a method that erases the space when more input is typed.

  • Related