1

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?

  • 1
    Just in case you are reinventing the wheel: `android:inputType="number"` see http://stackoverflow.com/questions/4645119/how-to-set-only-numeric-value-for-edittext-in-android. – Orkun Feb 24 '12 at 17:13
  • I've used it on my activity.xml but my problem is when a I press the Key, It doesn't appears on my EditText but It generates a KeyEvent. Can I do both at time? – Pep Aguiló Feb 24 '12 at 17:29

1 Answers1

1

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.

Community
  • 1
  • 1
Orkun
  • 6,998
  • 8
  • 56
  • 103
  • Many thanks @Zortkun for your interest. I'm using `inputType` in `xml` already. I'm asking that because I want to do a widget with two `EditText`. As I put numbers in one `EditText`, the other is filled with an arithmetic conversion, for this reason, I want to do an event and fill as well. – Pep Aguiló Feb 24 '12 at 18:42
  • Hey. Thanks for accepting as answer but I guess you a have different problem. I ll update and suggest some approaches for you. – Orkun Feb 25 '12 at 22:07