Android-->輕鬆打造帶刪除按鈕的輸入框(EditText),附Emoji表情過濾

來源:互聯網
上載者:User

標籤:textutils   需要   empty   copy   als   基礎   int   split   lines   

輸入框帶刪除按鈕, 此乃標配, 實現起來方法也很多, 網上開源也很多.

但是, 沒事就喜歡瞎折騰.

說話.

只是在原生的基礎上加了擴充. 相對來說入侵非常少, 使用方法和原生的一模一樣.無任何閹割.

完整代碼:

public class ExEditText extends AppCompatEditText {    Rect clearRect = new Rect();    public ExEditText(Context context) {        super(context);    }    public ExEditText(Context context, AttributeSet attrs) {        super(context, attrs);    }    public ExEditText(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    @Override    protected void onAttachedToWindow() {        super.onAttachedToWindow();        //在不影響預設過濾規則的情況下,添加Emoji表情過濾        if ("emoji".equalsIgnoreCase(String.valueOf(getTag()))) {            final InputFilter[] filters = getFilters();            final InputFilter[] newFilters = new InputFilter[filters.length + 1];            System.arraycopy(filters, 0, newFilters, 0, filters.length);            newFilters[filters.length] = new EmojiFilter();            setFilters(newFilters);        }    }    @Override    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {        super.onFocusChanged(focused, direction, previouslyFocusedRect);        //焦點改變,檢查是否需要顯示刪除按鈕        checkEdit(focused);    }    @Override    protected void onSizeChanged(int w, int h, int oldw, int oldh) {        super.onSizeChanged(w, h, oldw, oldh);        //用來計算刪除按鈕所在的矩形地區        clearRect.set(w - getPaddingRight() - Math.min(w, h), getPaddingTop(), w - getPaddingRight(), Math.min(w, h) - getPaddingBottom());    }    @Override    public boolean onTouchEvent(MotionEvent event) {        //檢查點擊刪除按鈕地區,並且當前具有焦點        if (event.getAction() == MotionEvent.ACTION_DOWN && isFocused()) {            //檢查是否在刪除按鈕矩形地區,按下            if (checkClear(event.getX(), event.getY())) {                //如果當前已經是空的, 不處理Touch事件,否則清空文本,達到刪除的效果                if (!TextUtils.isEmpty(getText())) {                    setText("");                    return true;                }            }        }        return super.onTouchEvent(event);    }    private void checkEdit(boolean focused) {        if (TextUtils.isEmpty(getText()) || !focused) {            setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);        } else {            //這裡才是關鍵, 用的是原生的方法顯示刪除表徵圖.            setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.base_edit_delete, 0);        }    }    //座標是否在按鈕區    private boolean checkClear(float x, float y) {        return clearRect.contains(((int) x), (int) y);    }    @Override    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {        super.onTextChanged(text, start, lengthBefore, lengthAfter);        //時刻檢查一下        checkEdit(true);    }}

Emoji表情過濾:

可能還是有些特殊的Emoji表情,或者字元表情無法過濾, 抱歉;
如果你發現, 請告知, 讓我們一起完善一下, 謝謝!

public class EmojiFilter implements InputFilter {    Pattern emojiPattern = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",            Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);    private int mMax = -1;//預設不過濾長度    public EmojiFilter() {    }    public EmojiFilter(int max) {        mMax = max;    }    /**     * 檢測是否有emoji表情     *     * @param source     * @return     */    public static boolean containsEmoji(CharSequence source) {        int len = source.length();        for (int i = 0; i < len; i++) {            char codePoint = source.charAt(i);            if (!isEmojiCharacter(codePoint)) { //如果不能匹配,則該字元是Emoji表情                return true;            }        }        return false;    }    /**     * 判斷是否是Emoji     *     * @param codePoint 比較的單個字元     * @return     */    private static boolean isEmojiCharacter(char codePoint) {        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) ||                (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000)                && (codePoint <= 0x10FFFF));    }    @Override    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,                               int dend) {        if (this.emojiPattern.matcher(source).find() || containsEmoji(source)) {            return "";        }        if (mMax != -1) {            int keep = mMax - (dest.length() - (dend - dstart));            if (keep <= 0) {                return "";            } else if (keep >= end - start) {                return null; // keep original            } else {                keep += start;                if (Character.isHighSurrogate(source.charAt(keep - 1))) {                    --keep;                    if (keep == start) {                        return "";                    }                }                return source.subSequence(start, keep);            }        }        return source;    }}

至此: 文章就結束了,如有疑問: QQ群 Android:274306954 Swift:399799363 歡迎您的加入.

Android-->輕鬆打造帶刪除按鈕的輸入框(EditText),附Emoji表情過濾

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.