Android-EditText控制输入范围在0~100之间

需求是,在EditText中输入数字,而且数字范围在0到100。贴出代码如下:

        edit.addTextChangedListener(new TextWatcher(){
            int l=0;////////记录字符串被删除字符之前,字符串的长度
            int location=0;//记录光标的位置

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub
                l=s.length();
                location=edit.getSelectionStart();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
                Pattern p = Pattern.compile("^(100|[1-9]\\d|\\d)$");

                Matcher m =p.matcher(s.toString());
                if(m.find() || ("").equals(s.toString())){
                    System.out.print("OK!");
                }else{
                    System.out.print("False!");
                    Toast.makeText(context, "请输入正确的数值", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }});

xml中添加

android:inputType="number"

你可能感兴趣的:(Android基础)