averageman
averageman

Reputation: 923

OnKeyListener changing EditText

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);

Upvotes: 0

Views: 226

Answers (2)

Riad
Riad

Reputation: 3850

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;       
}

Upvotes: 1

RScottCarson
RScottCarson

Reputation: 980

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).

Upvotes: 1

Related Questions