I want to intercept 0 to 9 button key events from soft keyboard in android. I have tried many ways but didn't succeed. any little help will help me a lot.
what I am doing is,
@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 custom EditText class but it is not working what am i missing? i have tried many key codes but no result in hand.
Use a text watcher, its 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 restrict the entry on your Edit Text to only alphabets add this in the XML of your edit text control:
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
If you dont like the above and want to achieve this through 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 "";
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With