0

I am trying to use OnKeyListener to change the content of an EditText depending on the entry but I am having problems doing that as it seems like it is being called twice.

Here is a shortened version of the code:

public class MyKeyListener implements View.OnKeyListener{ EditText et; public MyKeyListener(EditText editText){ this.et = editText; } public boolean onKey(View v, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_0){ this.et.setText("0"); } else { this.et.setText("1"); } } } 

and in the main activity I have this:

EditText et = (EditText) findViewById(R.id.myET); MyKeyListener mkl = new MoneyKeyListener(et); et.setOnKeyListener(mkl); 

2 Answers 2

1

Are you using a hardware keyboard? According to the documentation soft keyboards do not have to call onKeyListener callbacks. That being said, the reason you're seeing it called twice is because there is an onKeyDown event and an onKeyUp event. In your onKey(...) method you should check the KeyEvent to react to the intended event (down or up).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I will check that! As for keyboard, I am using a soft keyboard but I don't see any other way of detecting backspace key (I was previously using a TextWatcher but that doesn't detect backspaces...)
1

For twice calling the event, I think you know it from the answer of @RScottCarson. For softkeyboard you are using, can detect backspace by the following:

@Override public boolean onKey(View v, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_DEL) { // for backspace...check } //rest of the code return false; } 

2 Comments

But isn't that only guaranteed to work for hard keyboards?
i think for soft also ...you may try

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.