Intercept number 0-9 in Android EditText

I want to capture 0 to 9 events of a button from a soft keyboard in Android. I tried many ways, but could not. any little help will help me a lot.

What am I doing,

@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode==KeyEvent.KEYCODE_12) { Toast.makeText(context, "Pressed", Toast.LENGTH_LONG).show(); return true; } return super.onKeyDown(keyCode, event); } 

in my EditText class, but it doesn't work, what am I missing? I tried a lot of key codes, but no results in my hand.

+6
source share
1 answer

Using a text observer is much simpler:

At class level:

 EditText editText; 

in onCreate:

 editText = (EditText)findViewById(R.id.yourEdittext) editText.addTextChangedListener(mTextEditorWatcher); 

Outside onCreate (Class Level):

 final TextWatcher mTextEditorWatcher = new TextWatcher(){ public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { System.out.println("Entered text: "+editText.getText()); // USe edit_text.getText(); here } public void afterTextChanged(Editable s) { } }; 

If you want to limit the entry in the text editor to alphabets only, add this to the XML of your text control:

  android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" 

If you don't like the above and want to achieve this with code, use the following:

 editText.setFilters(new InputFilter[] { new InputFilter() { public CharSequence filter(CharSequence chr, int start, int end, Spanned dst, int dstart, int dend) { if(chr.equals("")){ return chr; } if(chr.toString().matches("[a-zA-Z ]+")){ return chr; } return ""; } } }); 
+2
source

Source: https://habr.com/ru/post/980653/


All Articles