1

I need to control pressed buttons, before they goes to my EditText widget. It's should work like filter. For example: I need that user could fill EditText only with digits 1,2,3,4,5 other symbols must be ignored. So the part of buttons on virtual keyboard should be disabled or I need to catch last pressed symbol, analyze it and disable for EditText.

Who knows the way how to solve this problem?

Thanks..

Dimon
  • 790
  • 1
  • 10
  • 24

2 Answers2

0
    statusEdt.addTextChangedListener(new TextWatcher(){
        public void afterTextChanged(Editable s) {}
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //do stuff
            charTxt.setText(statusEdt.getText().length() + "/140");
        }
    });

I used this TextChangedListener(TextWatcher) to keep a count of how many characters had been typed into an EditText for a Twitter client I made. You could probably use a listener like this. You'll want to override beforeTextChanged or onTextChanged. These methods will pass you whatever CharSequence has been typed. You can check what was typed in and if it is not valid input you can remove it by calling setText() and passing in whatever has been typed so far minus the invalid characters.

FoamyGuy
  • 46,603
  • 18
  • 125
  • 156
  • Yes, I know about .addTextChangedListener(TextWatcher) method, and I'm using it in my applications. Before I asked here a question, I experimentally tried to use 3 events (afterTextChanged, beforeTextChanged, onTextChanged) and for easy way for check just set for everyone s = "asdf", but this text doesn't appear in my EditText. As result, I can't change the typed value. Moreover, I really tried to do a filter, and when I so that the typed symbol was wrong, just removed last added symbol from EditText. But this action move EditText cursor to first position. – Dimon Sep 21 '11 at 00:28
  • It's wrong way to check LAST added symbol, cause user can move cursor and type new symbol anywhere. That means I need to "scan" every time whole string for the "wrong" symbols... it's difficult way, I can do that, but I feel this is wrong way. I think there must be more beautiful and short way to do that... that why I'm here – Dimon Sep 21 '11 at 00:28
0

What you probably need is an InputFilter. For example to allow only digits, sign and decimal point:

 editText.setFilters(DigistKeyListener.getInstance(true, true));
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
  • You know, you showed me the right way to search the answer on my question. I found a detailed description right here http://stackoverflow.com/questions/3349121/how-do-i-use-inputfilter-to-limit-characters-in-an-edittext-in-android – Dimon Sep 23 '11 at 00:09
  • DigitsKeyListener.getInstance() can work if you only allow digits. – Diego Torres Milano Sep 23 '11 at 01:48