关于EditText的一些操作扩展

相关方法如下:

import android.content.Context
import android.text.Editable
import android.text.InputFilter
import android.text.InputType
import android.text.TextUtils
import android.text.TextWatcher
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import com.szhg9.magicworkep.common.utils.EditTextUtils
import org.jetbrains.anko.collections.forEachWithIndex

/**
 * 过滤emoji
 */
fun EditText.filterEmoji() {
    var arrys = arrayOfNulls(filters.size+1)
    filters.forEachWithIndex { index, inputFilter ->
        arrys[index] = inputFilter
    }
    arrys[filters.size] = EditTextUtils.getInputFilterProhibitEmoji()
    filters = arrys
}

/**
 * 过滤标点
 */
fun EditText.filterSp() {
    var arrys = arrayOfNulls(filters.size+1)
    filters.forEachWithIndex { index, inputFilter ->
        arrys[index] = inputFilter
    }
    arrys[filters.size] = EditTextUtils.getInputFilterProhibitSP()
    filters = arrys
}

/**
 * 过滤emoji和标点
 */
fun EditText.filterSpAndEmoji() {
    var arrys = arrayOfNulls(filters.size+2)
    filters.forEachWithIndex { index, inputFilter ->
        arrys[index] = inputFilter
    }
    arrys[filters.size] = EditTextUtils.getInputFilterProhibitSP()
    arrys[filters.size+1] =  EditTextUtils.getInputFilterProhibitEmoji()
    filters = arrys
}

/**
 * 对输入的金额进行格式化处理
 */
fun EditText.FormatMoney(back:((String)->(Unit))?) {
    var et = this
    var input = ""
    this.addTextChangedListener(object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}

        override fun afterTextChanged(s: Editable) {
            var str = et.text?.toString()!!.trim()
            //用于处理多个小数点输入问题
            if (!TextUtils.isEmpty(str) && str.indexOf(".") != str.lastIndexOf(".")) {
                et.setText(input)
                et.setSelection(et.text!!.length)//将光标移至文字末尾
                return
            }
            //控制输入时只能输入1个0
            if (!TextUtils.isEmpty(str) && str == "00") {
                et.setText("0")
                et.setSelection(et.text!!.length)//将光标移至文字末尾
                return
            }
            //控制输入时第一个为0第二位不为.的情况
            if (!TextUtils.isEmpty(str) && str.length >= 2 && str.indexOf("0") == 0 && str.indexOf(".") != 1) {
                et.setText(str.substring(1, str.length))
                et.setSelection(et.text!!.length)//将光标移至文字末尾
                return
            }
            input = str
            //用于处理限制输入小数点后2位问题
            val index = et.text?.indexOf(".")
            if (index!! > 0 && index < et.text?.length!! - 3) {
                val str = et.text?.substring(0, et.text?.toString()?.trim()?.indexOf(".")!! + 3)
                et.setText(str)
                et.setSelection(et.text!!.length)//将光标移至文字末尾
            }
            if (index == 0) {
                et.setText("0" + et.text!!)
                et.setSelection(et.text!!.length)//将光标移至文字末尾
            }
            back?.invoke(str)
        }
    })
}

/**
 * 对输入的内容进行格式化处理
 * 使输入的数字大于0
 */
fun EditText.formatNum(back:((String?)->(Unit))?=null) {
    inputType = InputType.TYPE_CLASS_NUMBER
    var et = this
    this.addTextChangedListener(object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}

        override fun afterTextChanged(s: Editable) {
            var str = et.text?.toString()!!.trim()
            //控制输入时只能输入1个0
            if (!TextUtils.isEmpty(str)&&str.startsWith("0")&&str!="0") {
                try {
                    et.setText(str.toInt().toString())
                    et.setSelection(str.length)
                } catch (e: Exception) {
                    et.setText("1")
                }
            }
            back?.invoke(str)
        }
    })
}

/**
 * 添加键盘搜索监听
 */
fun EditText.addEditorActionListener(search: ((String?) -> (Unit))?) {
    setOnEditorActionListener { v, actionId, _ ->
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            search?.invoke(text.toString())
            val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm?.hideSoftInputFromWindow(v.windowToken, 0)
        }
        false
    }
}

相关标点和表情过滤如下:

package com.szhg9.magicworkep.common.utils;

import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.widget.EditText;

import com.jess.arms.utils.ArmsUtils;
import com.szhg9.magicworkep.R;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EditTextUtils {
    /**
     * 禁止EditText输入空格
     *
     * @param editText
     */
    public static void setEditTextInhibitInputSpace(EditText editText) {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.equals(" ")) {
                    return "";
                } else {
                    return null;
                }
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }

    /**
     * 禁止EditText输入特殊字符
     *
     * @param editText
     */
    public static void setEditTextInhibitInputSpeChat(EditText editText) {

        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.equals(" ")) {
                    return "";
                } else {
                    String speChat = "[`~~!@#$%^&*()+-=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
                    Pattern pattern = Pattern.compile(speChat);
                    Matcher matcher = pattern.matcher(source.toString());
                    if (matcher.find()) return "";
                    else return null;
                }
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }


    public static void setLengthInputFilter(EditText editText, final int maxLength){

        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                int dindex = 0;
                int count = 0;

                while (count <= maxLength && dindex < dest.length()) {
                    char c = dest.charAt(dindex++);
                    if (c < 128) {
                        count = count + 1;
                    } else {
                        count = count + 2;
                    }
                }

                if (count > maxLength) {
                    return dest.subSequence(0, dindex - 1);
                }

                int sindex = 0;
                while (count <= maxLength && sindex < source.length()) {
                    char c = source.charAt(sindex++);
                    if (c < 128) {
                        count = count + 1;
                    } else {
                        count = count + 2;
                    }
                }

                if (count > maxLength) {
                    sindex--;
                }

                return source.subSequence(0, sindex);
            }
        };

        editText.setFilters(new InputFilter[]{filter});
    }

    /**
     * 禁止EditText输入特殊字符
     */
    public static class InhibitInputSpeChatFilter implements InputFilter{
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            if (source.equals(" ")) {
                return "";
            } else {
                String speChat = "[-`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
                Pattern pattern = Pattern.compile(speChat);
                Matcher matcher = pattern.matcher(source.toString());
                if (matcher.find()) return "";
                else return null;
            }
        }
    }

    /**
     * 限制EditText最大长度 中文2个字节, 英文1个字节
     */
    public static class LengthInputFilter implements InputFilter {
        private int maxLen = 0;

        public LengthInputFilter(int maxLen) {
            this.maxLen = maxLen;
        }

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            int dindex = 0;
            int count = 0;

            while (count <= maxLen && dindex < dest.length()) {
                char c = dest.charAt(dindex++);
                if (c < 128) {
                    count = count + 1;
                } else {
                    count = count + 2;
                }
            }

            if (count > maxLen) {
                return "";
            }

            int sindex = 0;
            while (count <= maxLen && sindex < source.length()) {
                char c = source.charAt(sindex++);
                if (c < 128) {
                    count = count + 1;
                } else {
                    count = count + 2;
                }
            }

            if (count > maxLen) {
                sindex--;
            }

            return source.subSequence(0, sindex);
        }
    }


    public static  InputFilter getInputFilterProhibitEmoji() {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend) {
                StringBuffer buffer = new StringBuffer();
                for (int i = start; i < end; i++) {
                    char codePoint = source.charAt(i);
                    if (!getIsEmoji(codePoint)) {
                        buffer.append(codePoint);
                    } else {
                        ArmsUtils.snackbarText("暂不支持表情输入");
                        i++;
                        continue;
                    }
                }
                if (source instanceof Spanned) {
                    SpannableString sp = new SpannableString(buffer);
                    TextUtils.copySpansFrom((Spanned) source, start, end, null,
                            sp, 0);
                    return sp;
                } else {
                    return buffer;
                }
            }
        };
        return filter;
    }

    public static boolean getIsEmoji(char codePoint) {
        if ((codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA)
                || (codePoint == 0xD)
                || ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
                || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
                || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)))
            return false;
        return true;
    }

    public static InputFilter getInputFilterProhibitSP() {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend) {
                StringBuffer buffer = new StringBuffer();
                for (int i = start; i < end; i++) {
                    char codePoint = source.charAt(i);
                    if (!getIsSp(codePoint)) {
                        buffer.append(codePoint);
                    } else {
                        ArmsUtils.snackbarText("暂不支持表情输入");
                        i++;
                        continue;
                    }
                }
                if (source instanceof Spanned) {
                    SpannableString sp = new SpannableString(buffer);
                    TextUtils.copySpansFrom((Spanned) source, start, end, null,
                            sp, 0);
                    return sp;
                } else {
                    return buffer;
                }
            }
        };
        return filter;
    }

    public static boolean getIsSp(char codePoint){
        if(Character.getType(codePoint)>Character.LETTER_NUMBER){
            return true;
        }
        return false;
    }
}

你可能感兴趣的:(关于EditText的一些操作扩展)