How to restrict the EditText input content

三世轮回 提交于 2019-12-06 03:47:15

You can use this digits attribute android:digits="0123456789"

You can use InputFilter limit characters in an EditText as:

EditText mEdit = (EditText)findViewById(R.id.mEdit);          
InputFilter[] filters = {new AdnNameLengthFilter()};  
mEdit.setFilters(filters);  
public static class AdnNameLengthFilter implements InputFilter  
    {  
        private int nMax;  

        public  CharSequence filter (CharSequence source, int start, int end, Spanned dest, int dstart, int dend)  
        {  
            Log.w("Android_12", "source("+start+","+end+")="+source+",dest("+dstart+","+dend+")="+dest);  

            if(dest.toString()=="."||( source.toString()==".")  
            {  
               //DO SOMTHING HERE  
            }else  
            {  
                //DO SOMTHING HERE
            }  
        }
    }

Second Option is TextWatcher for finding char input by user as:

mEditText = (EditText)findViewById(R.id.ET);
mEditText.addTextChangedListener(mTextWatcher);
TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int arg1, int arg2,
                int arg3) {
            // YOU STRING BEFORE CHANGE
        }
        @Override
        public void onTextChanged(CharSequence s, int arg1, int arg2,
                int arg3) {
              // CHARS INPUT BY USER
        }
        @Override
        public void afterTextChanged(Editable s) {
              // AFTER TEXT CCHANGE In EDITTEXT BY USER
        }
    };

Use TextWatcher to check each thing as it is entered and determine whether it should be allowed into the EditText or ignored.

Make yourself one and override its methods to implement whatever logic you want.

once you create your TextWatcher apply it to the EditText like this:

edt.addTextChangedListener(mTextWatcher);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!