Search code examples
androidkeylistenerkeyevent

OnKeyListener OnKey repeats action


I'm trying to modify the action when the user clicks the "DEL" key (on the screen keyboard), here's the code

ed.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_DEL) {
                if(contadorcor == 0){
                    String output = correctOutput(String.valueOf(ed.getText()));
                    ed.setText(output);
                    ed.setSelection(num);
                    contadorcor++;
                }
            }
            contadorcor = 0;
            return false;
        }
    });

public static String correctOutput(String s) {
    String input = s;
    int pos = 0;
    for (int i = 0; i < input.length(); i++) {
            if(input.charAt(i) != ' ') {
            if(input.charAt(i) != '_') {
                pos = i;
            }
        }
    }
    String output = "";
    for (int i = 0; i < input.length(); i++) {
        if(i != pos) {
            output = output + String.valueOf(input.charAt(i));
        } else {
            output = output + "_";
        }
    }
    num = num - 2;
    return output;
}

To understand why I do this its because there is an unknown word like this "_ _ _ _ _ _ _ _ ....." and when the user deletes a letter when trying to guess it, lets say "T H I S I K |_ _ ... " and wants to correct the "K" and the cursor is just at the start of the next "underscore" i want to delete the "k" and substitute it by a "underscore" then place the cursor there. "T H I S I |_ _ _ _ ...."

But when I press the delete key makes this action twice, and deletes 2 letters. I supose that captures keydown and keyup and thats why it repeats but i dont know how to fix it. I've tryed to make some kind of counter but it is not working either

Thanks in advance.


Solution

  • in the onKey method, you have an argument: event. You can do the following:

    if(event.getAction()==KeyEvent.ACTION_UP){
    ...
    }
    else if(event.getAction()==KeyEvent.ACTION_DOWN){
    ...
    }