Android EditText 实现特殊格式输入

现实中经常遇到要输入特殊格式的字符串,比如MAC地址,IP地址等,可以自动匹配需要的 格式。实现方式是通过EditText.addTextChangedListener(TextWatcher)

TextWatcher实现方式如下:

class MyTextWatcher implements TextWatcher{
        private boolean mWasEdited = false;
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {}

        @Override
        public void afterTextChanged(Editable s) {
            if(mWasEdited){
                mWasEdited = false;
                return;
            }
            mWasEdited = true;
            String newString;
            // 根据需求封装字符串
            
            // 替换字符串
            s.replace(0,s.length(),newString);
        }
    }


附上一段我在用的代码,实现MAC格式输入(格式:00-00-00-00-00-00)

class MacTextWatcher implements TextWatcher{
        private boolean mWasEdited = false;
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {}

        @Override
        public void afterTextChanged(Editable s) {
            if(mWasEdited){
                mWasEdited = false;
                return;
            }
            mWasEdited = true;
            String mac = s.toString();
            mac = mac.toUpperCase().replace("-","").replace(":","");
            StringBuilder builder = new StringBuilder();
            for(int i=0;i




你可能感兴趣的:(android)