Pep Aguiló
Pep Aguiló

Reputation: 57

setText on EditText with an EventKey

I'm trying to develop a widget with an EditText (only int allowed) and KeyEvent. The problem is when '0' is pressed, It detects the KeyEvent but It doesn't write the '0' on my EditText. It should add numbers in order I press them.

et1.setOnKeyListener(new OnKeyListener() {
    @Override 
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (KeyEvent.ACTION_UP != event.getAction()) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_0:
                    //Do something...
                    break;
                default: 
                    return false;
            }
        }
        return true;
    } 
});

I've tried to do something like that, but It isn't so efficient.

et1.setText(et1.getText().toString + "0");

Do you know some kind of solution?

Upvotes: 1

Views: 342

Answers (1)

Orkun
Orkun

Reputation: 7228

Let me try to make myself clear Pep:

1) If what you are trying to achieve is to have an EditText that allows only integer (numeric) input, you can add an attribute and that s it. You donT need a custom control for that behavior.

 android:inputType="number" 

2) The reason why you donT get any input in your EditText is simply because you are blocking it by returning true in the overridden onKey method.

The ref says, onKey should return:

True if the listener has consumed the event, false otherwise.

That means, if you are returning true, you are in charge, Android wont input anything in your EditText. Since you are not doing (at least in the code you provided) it yourself, EditText is not filled.

So, I ll suggest you should remove the handler altogether and add the inputType attribute in xml like you did before.


Update

If you need to update an EditText (let's call it EditText1) based on the input in another (EditText2), I suggest tracking the input in the first one with a TextWatcher and set the text EditText2 with the processed value.

Check this similar issue for sample code.

Upvotes: 1

Related Questions