How to restrict the EditText input content

删除回忆录丶 提交于 2019-12-22 10:01:11

问题


I am trying to create a simple calculator which provides the EditText for the users to input the numbers. The allowing input content should be [1,2,3,4,5,6,7,8,9,0,.]

I know that it is possible to limit the input content by using following code

android:digits="1234567890."
android:inputType="phone"

But how can I prevent the users from adding more than one dot (.) into the EditText Box?


回答1:


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




回答2:


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
        }
    };



回答3:


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


来源:https://stackoverflow.com/questions/10826566/how-to-restrict-the-edittext-input-content

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