在Android EditText中拦截0到9号

Hit*_*ani 6 android numbers android-edittext

我想从android中的软键盘拦截0到9个按键事件.我尝试了很多方法但没有成功.任何小小的帮助都会对我有所帮助.

我在做什么,

@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);
}
Run Code Online (Sandbox Code Playgroud)

在我的自定义EditText类但它不工作我错过了什么?我尝试了很多关键代码,但没有结果.

Sky*_*net 2

使用文本观察器,它更简单:

在班级层面:

EditText editText; 
Run Code Online (Sandbox Code Playgroud)

在 onCreate 中:

editText = (EditText)findViewById(R.id.yourEdittext)

editText.addTextChangedListener(mTextEditorWatcher);
Run Code Online (Sandbox Code Playgroud)

在 onCreate(类级别) 之外:

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) {

            }
        };
Run Code Online (Sandbox Code Playgroud)

如果您想将编辑文本中的条目限制为仅字母,请在编辑文本控件的 XML 中添加以下内容:

 android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
Run Code Online (Sandbox Code Playgroud)

如果您不喜欢上述内容并希望通过代码实现此目的,请使用以下内容:

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 "";
        }
    }
});
Run Code Online (Sandbox Code Playgroud)