zoukankan      html  css  js  c++  java
  • Android:EditText限制文字输入

         Android的编辑框控件EditText在平常编程时会经常用到,有时候会对编辑框增加某些限制,如限制只能输入数字,最大输入的文字个数,不能输入一些非法字符等,这些需求有些可以使用android控件属性直接写在布局xml文件里,比如android:numeric="integer"(只允许输入数字);

         对于一些需求,如非法字符限制(例如不允许输入#号,如果输入了#给出错误提示),做成动态判断更方便一些,而且容易扩展;

         在Android里使用TextWatcher接口可以很方便的对EditText进行监听;TextWatcher中有3个函数需要重载:

        public void beforeTextChanged(CharSequence s, int start,
                                      int count, int after);
        public void onTextChanged(CharSequence s, int start, int before, int count);
        public void afterTextChanged(Editable s);

         从函数名就可以知道其意思,每当敲击键盘编辑框的文字改变时,上面的三个函数都会执行,beforeTextChanged可以给出变化之前的内容,onTextChanged和afterTextChanged给出追加上新的字符之后的文本;

    所以对字符的限制判断可以在afterTextChanged函数中进行,如果检查到新追加的字符为认定的非法字符,则在这里将其delete掉,那么他就不会显示在编辑框里了:

    private final TextWatcher mTextWatcher = new TextWatcher() {
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        } 
    
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        } 
    
        public void afterTextChanged(Editable s) {
            if (s.length() > 0) {
                int pos = s.length() - 1;
                char c = s.charAt(pos);
                if (c == '#') {
    //这里限制在字串最后追加#
                    s.delete(pos,pos+1);
                    Toast.makeText(MyActivity.this, "Error letter.",Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

         注册监听:

    EditText mEditor = (EditText)findViewById(R.id.editor_input);
    mEditor.addTextChangedListener(mTextWatcher);
  • 相关阅读:
    day52—JavaScript拖拽事件的应用(自定义滚动条)
    day51—JavaScript绑定事件
    day50—JavaScript鼠标拖拽事件
    day49—JavaScript阻止浏览器默认行为
    day48—JavaScript键盘事件
    day47—JavaScript事件基础应用
    day41—JavaScript运动的停止条件
    Java Web项目使用图形验证码 — Kaptcha
    Disconf-Web管理端安装
    Git基本常用指令
  • 原文地址:https://www.cnblogs.com/flyme/p/2143047.html
Copyright © 2011-2022 走看看