我的Material Design EditText,實現(xiàn)刪除功能

我的Material Design EditText,實現(xiàn)刪除功能

本文原創(chuàng),轉載請注明出處。歡迎關注我的 簡書。
github:MyDemo喜歡的話就給個Star
安利一波我寫的開發(fā)框架:MyScFrame喜歡的話就給個Star

前言:

Material Design推出了一種優(yōu)秀的文本輸入框形式——當用戶點擊空內(nèi)容的文本輸入框時,原本位于輸入框內(nèi)的提示語會經(jīng)由一個動畫浮動至輸入框上方,文本顏色同時變成強調色,明確顯示此時該組件獲得焦點
為了讓開發(fā)者更加方便地實現(xiàn)這種效果Google推出了TextInputLayout組件,里面放置一個EditText或者TextInputEditText,可以輕松實現(xiàn)

附上效果圖

大體效果如圖

添加依賴

compile 'com.android.support:appcompat-v7:25.1.0'
compile 'com.android.support:design:25.1.0'

TextInputLayout常用屬性以及用法

布局中的名稱 參數(shù)類型 代碼中的方法名稱 注解
counterEnabled boolean setCounterEnabled(boolean) 用于設置字符計數(shù)器的開啟或關閉
counterMaxLength int setCounterMaxLength(int) 設置字符計數(shù)器的最大長度。(僅用于設置計數(shù)器最大值,并不影響文本實際能輸入的最大長度)
errorEnabled boolean setErrorEnabled(boolean) 用于設置錯誤提示是否開啟。
hint String setHint(CharSequence) 設置輸入框的提示語。
hintAnimationEnabled boolean setHintAnimationEnabled(boolean) 開啟或關閉hint浮動成標簽的動畫效果。
hintEnabled boolean setHintEnabled(boolean) 開啟或關閉hint浮動的功能,設為false的話就和之前的EditText一樣,在輸入文字后,提示語就消失了。
hintTextAppearance style setHintTextAppearance(int) 設置hint的style,字體顏色,字體大小等,可引用系統(tǒng)自帶的也可以自定義。若要使用請統(tǒng)一使用,以保證APP體驗的統(tǒng)一性。
passwordToggleEnabled boolean setPasswordVisibilityToggleEnabled(boolean) 控制密碼可見開關是否啟用。設為false則該功能不啟用,密碼輸入框右側也沒有控制密碼可見與否的開關。
passwordToggleDrawable Drawable setPasswordVisibilityToggleDrawable(Drawable) 設置密碼可見開關的圖標。通常我們會在不同的情況下設定不同的圖標,可通過自定義一個selector,根據(jù)“state_checked”屬性來控制圖標的切換。
passwordToggleTint Color setPasswordVisibilityToggleTintList(ColorStateList) 控制密碼可見開關圖標的顏色。在開啟或關閉的狀態(tài)下我們可以設定不同的顏色,可通過自定義一個color的selector,根據(jù)“state_checked”和“state_selected”屬性來控制顏色的切換。
passwordToggleTintMode PorterDuff.Mode setPasswordVisibilityToggleTintMode(PorterDuff.Mode) 控制密碼可見開關圖標的背景顏色混合模式。這個地方我不是很能理解,希望有人可以指教。
passwordToggleContentDescription int setPasswordVisibilityToggleContentDescription(int) 該功能是為Talkback或其他無障礙功能提供的。TalkBack會去讀contentDescription的值,告訴用戶這個操作是什么。

passwordToggleTintMode相關知識有興趣請參考Xfermode in android 其中有關于這方面概念的解釋。

layout布局

<?xml version="1.0" encoding="utf-8"?>
<!--
TextInputLayout:
    app:hintEnabled="true"http://設置是否可以使用hint屬性,默認是true
    app:hintAnimationEnabled="true"http://設置是否可以使用動畫,默認是true
    app:hintTextAppearance="@style/hintAppearance"http://設置hint的文本屬性,改變hint文字的大小顏色等屬性
    app:counterEnabled="true"http://設置是否可以開啟計數(shù)器,默認是false
    app:counterOverflowTextAppearance="@style/counterOverflowTextAppearance"http://設置計算器越位后的文字顏色和大小
    app:counterTextAppearance="@style/hintAppearance"http://設置正常情況下的計數(shù)器文字顏色和大小
    app:counterMaxLength="11"http://設置計算器的最大字數(shù)限制
    app:errorEnabled="true"http://是否允許錯誤提示,默認是true
    app:errorTextAppearance="@style/errorAppearance"http://錯誤提示的文字大小和顏色
    app:passwordToggleEnabled="true"http://設置是否顯示密碼眼睛,默認是false
    app:passwordToggleDrawable="@mipmap/ic_launcher"http://自定義眼睛圖標
    app:passwordToggleTint="@color/colorAccent"http://給眼睛著色
    app:passwordToggleTintMode="multiply"http://選擇著色模式,與passwordToggleTint一起用
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:orientation="vertical">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/widget_textinput_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/TextInputLayoutLineColor"
        app:counterEnabled="true"
        app:counterMaxLength="11"
        app:counterOverflowTextAppearance="@style/counterOverflowTextAppearance"
        app:errorTextAppearance="@style/errorAppearance"
        app:hintTextAppearance="@style/hintAppearance">

        <com.caihan.mydemo.widget.edittext.AutoCheckEditText
            android:id="@+id/widget_et"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawableEnd="@drawable/v2_et_del_image"
            android:drawableStart="@drawable/v2_register_phone"
            android:hint="請輸入用戶名"
            android:imeOptions="actionNext"
            android:inputType="number"
            android:singleLine="true"/>
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/widget_textinput_layout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/TextInputLayoutLineColor"
        app:counterEnabled="true"
        app:counterMaxLength="11"
        app:counterOverflowTextAppearance="@style/counterOverflowTextAppearance"
        app:errorTextAppearance="@style/errorAppearance"
        app:hintTextAppearance="@style/hintAppearance"
        app:passwordToggleEnabled="true"
        app:passwordToggleTint="@color/colorAccent">

        <com.caihan.mydemo.widget.edittext.AutoCheckEditText
            android:id="@+id/widget_et2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawableStart="@drawable/v2_login_pwd"
            android:hint="請輸入密碼"
            android:imeOptions="actionDone"
            android:inputType="textPassword"
            android:singleLine="true"/>
    </android.support.design.widget.TextInputLayout>
</LinearLayout>

Style

<!--EditText的主題 Start-->
<style name="TextInputLayoutLineColor" parent="Theme.AppCompat.Light">
    <!--沒有獲取焦點時的顏色-->
    <item name="colorControlNormal">@color/colorAccent</item>
    <!--獲取焦點時的顏色-->
    <item name="colorControlActivated">@color/main_color</item>
</style>

<!--浮動標簽-->
<style name="hintAppearance" parent="TextAppearance.AppCompat">
    <item name="android:textSize">14sp</item>
    <item name="android:textColor">@color/colorPrimary</item>
</style>

<!--錯誤提示信息-->
<style name="errorAppearance" parent="TextAppearance.AppCompat">
    <item name="android:textSize">14sp</item>
    <item name="android:textColor">@android:color/holo_red_light</item>
</style>

<!--超出計數(shù)最大長度,浮動標簽,下劃線,計數(shù)文字都會改變顏色-->
<style name="counterOverflowTextAppearance" parent="TextAppearance.AppCompat">
    <item name="android:textSize">14sp</item>
    <item name="android:textColor">@android:color/holo_red_dark</item>
</style>
<!--EditText的主題 End-->

模塊化

我喜歡吧一個一個功能或者幾個功能打包起來當成一個模塊,然后項目由一個一個模塊組成,每個模塊之間是完全解耦的,這樣有利于后期的維護跟修改
先來看看結構


AutoCheckEditText

WarnViewStatus

/**
 * Created by caihan on 2016/9/16.
 * 警告語顯示監(jiān)聽
 */
public interface WarnViewStatus {
    /**
     * 展示警告語
     *
     * @param msgs
     */
    void show(String... msgs);

    /**
     * 隱藏警告語
     */
    void hide();
}

WarningMsg

/**
 * Created by caihan on 2017/1/22.
 * 錯誤提示語
 */
public class WarningMsg {
    private static final String TAG = "WarningMsg";
    private int mType;
    private String mMsgString;

    public WarningMsg(int typ) {
        setType(typ);
    }

    private void setType(int typ) {
        mType = typ;
    }

    /**
     * 正則判斷錯誤的提示語
     * @return
     */
    public String getMsg() {
        switch (mType) {
            case EditTextType.TYPE_OF_MOBILE:
                //手機校驗
                mMsgString = "請輸入正確手機號碼";
                break;
            case EditTextType.TYPE_OF_TEL:
                //座機校驗
                mMsgString = "請輸入正確座機號碼";
                break;
            case EditTextType.TYPE_OF_EMAIL:
                //郵箱校驗
                mMsgString = "請輸入正確郵箱";
                break;
            case EditTextType.TYPE_OF_URL:
                //url校驗
                mMsgString = "請輸入正確地址";
                break;
            case EditTextType.TYPE_OF_CHZ:
                //漢字校驗
                mMsgString = "請輸入正確中文";
                break;
            case EditTextType.TYPE_OF_USERNAME:
                //用戶名校驗
                mMsgString = "請輸入正確用戶名";
                break;
            case EditTextType.TYPE_OF_USER_DEFINE:
                mMsgString = "";
                break;
            default:
                mMsgString = "";
                break;
        }
        return mMsgString;
    }

    /**
     * 不符合長度要求的提示語
     *
     * @return
     */
    public String getLengthMsg() {
        mMsgString = "不符合要求";
        return mMsgString;
    }

    public String getMinLengthMsg() {
        mMsgString = "不符合要求";
        return mMsgString;
    }

    public String getMaxLengthMsg() {
        mMsgString = "不符合要求";
        return mMsgString;
    }
}

EditTextType

/**
 * Created by caihan on 2017/1/22.
 */
public interface EditTextType {

    //手機校驗類型
    int TYPE_OF_MOBILE = 0xb0;
    //座機校驗類型
    int TYPE_OF_TEL = 0xb1;
    //郵箱校驗類型
    int TYPE_OF_EMAIL = 0xb2;
    //url校驗類型
    int TYPE_OF_URL = 0xb3;
    //漢字校驗類型
    int TYPE_OF_CHZ = 0xb4;
    //用戶名校驗類型
    int TYPE_OF_USERNAME = 0xb5;
    //用戶自定義
    int TYPE_OF_USER_DEFINE = 0xbb;
}

Check

/**
 * Created by caihan on 2017/1/16.
 * 正則判斷
 */
public class Check {
    private static final String TAG = "Check";
    //驗證座機號,正確格式:xxx/xxxx-xxxxxxx/xxxxxxxx
    private static final String REGEX_TEL = "^0\\d{2,3}[- ]?\\d{7,8}";

    public static boolean getMatch(int typ, String string, String... userRegxs) {
        boolean isMatch = false;
        switch (typ) {
            case EditTextType.TYPE_OF_MOBILE:
                isMatch = isMobile(string);
                break;
            case EditTextType.TYPE_OF_TEL:
                isMatch = isTel(string);
                break;
            case EditTextType.TYPE_OF_EMAIL:
                isMatch = isEmail(string);
                break;
            case EditTextType.TYPE_OF_URL:
                isMatch = isURL(string);
                break;
            case EditTextType.TYPE_OF_CHZ:
                isMatch = isChz(string);
                break;
            case EditTextType.TYPE_OF_USERNAME:
                isMatch = isUsername(string);
                break;
            case EditTextType.TYPE_OF_USER_DEFINE:
                if (userRegxs != null && userRegxs.length > 0 && !StringUtils.isEmpty(userRegxs[0])) {
                    isMatch = isMatch(userRegxs[0], string);
                }
                break;
            default:
                break;
        }
        return isMatch;
    }

    /**
     * @param string 待驗證文本
     * @return 是否符合手機號格式
     */
    private static boolean isMobile(String string) {
        return RegexUtils.isMobileSimple(string);
    }

    /**
     * @param string 待驗證文本
     * @return 是否符合座機號碼格式
     */
    private static boolean isTel(String string) {
        return RegexUtils.isMatch(REGEX_TEL, string);
    }

    /**
     * @param string 待驗證文本
     * @return 是否符合郵箱格式
     */
    private static boolean isEmail(String string) {
        return RegexUtils.isEmail(string);
    }

    /**
     * @param string 待驗證文本
     * @return 是否符合網(wǎng)址格式
     */
    private static boolean isURL(String string) {
        return RegexUtils.isURL(string);
    }

    /**
     * @param string 待驗證文本
     * @return 是否符合漢字
     */
    private static boolean isChz(String string) {
        return RegexUtils.isZh(string);
    }

    /**
     * @param string 待驗證文本
     * @return 是否符合用戶名
     */
    private static boolean isUsername(String string) {
        return RegexUtils.isUsername(string);
    }

    /**
     * 判斷是否匹配正則
     *
     * @param regex 正則表達式
     * @param input 要匹配的字符串
     * @return {@code true}: 匹配<br>{@code false}: 不匹配
     */
    private static boolean isMatch(String regex, CharSequence input) {
        return RegexUtils.isMatch(regex, input);
    }
}

上面這些類基本上都沒什么可說的,我不習慣把所有東西都放在一個類里面,所以分了好多個類出來,個人習慣問題.
下面開始說下AutoCheckEditText這個類實現(xiàn)了刪除按鈕正則判斷
注解都寫的比較詳細,就不重復說明了,如果有不懂的地方再問我

/**
 * Created by caihan on 2017/1/16.
 */
public class AutoCheckEditText extends TextInputEditText implements TextWatcher, View.OnFocusChangeListener {
    private static final String TAG = "AutoCheckEditText";

    private Context mContext;
    private int mType;
    private Drawable successDrawable;
    private Drawable unsuccessDrawable;
    private String userRegx;
    //左邊圖標
    private Drawable mLeftDrawable;
    //右側刪除圖標
    private Drawable mRightDrawable;
    private final int DRAWABLE_LEFT = 0;
    private final int DRAWABLE_TOP = 1;
    private final int DRAWABLE_RIGHT = 2;
    private final int DRAWABLE_BOTTOM = 3;
    private WarnViewStatus mWarnViewListener;
    private WarningMsg mWarningMsg;
    private int mMinLength = 0;
    private int mMaxLength = Integer.MAX_VALUE;

    public AutoCheckEditText(Context context) {
        super(context);
        init(context);
    }

    public AutoCheckEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public AutoCheckEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }


    private void init(Context context) {
        if (context == null) return;
        mContext = context;
        mRightDrawable = getCompoundDrawablesRelative()[DRAWABLE_RIGHT];
        mLeftDrawable = getCompoundDrawablesRelative()[DRAWABLE_LEFT];
//        this.setImeOptions(EditorInfo.IME_ACTION_DONE);
//        this.setInputType(EditorInfo.TYPE_CLASS_TEXT);
        setCompoundDrawablesRelativeWithIntrinsicBounds(mLeftDrawable, null, null, null);
        this.addTextChangedListener(this);
        this.setOnFocusChangeListener(this);
    }

    /**
     * @param typ            要校驗的類型
     * @param warnViewStatus 錯誤提示語狀態(tài)監(jiān)聽
     */
    public void creatCheck(int typ, WarnViewStatus warnViewStatus) {
        this.mType = typ;
        mWarningMsg = new WarningMsg(typ);
        mWarnViewListener = warnViewStatus;
    }

    /**
     * 設置判斷的長度區(qū)間
     *
     * @param minLength
     * @param maxLength
     */
    public void setLength(int minLength, int maxLength) {
        setMinLength(minLength);
        setMaxLength(maxLength);
    }

    public void setMinLength(int minLength) {
        mMinLength = minLength;
    }

    public void setMaxLength(int maxLength) {
        mMaxLength = maxLength;
    }

    /**
     * @param typ       要校驗的類型
     * @param success   匹配成功時的圖標
     * @param unsuccess 匹配失敗時的圖標
     * @param userRegex 用戶自定義正則
     */
    public void creatCheck(int typ, Drawable success, Drawable unsuccess, String userRegex) {
        creatCheck(typ, success, unsuccess);
        this.userRegx = userRegex;
    }

    /**
     * @param typ       要校驗的類型
     * @param success   匹配成功時的圖標
     * @param unsuccess 匹配失敗時的圖標
     */
    private void creatCheck(int typ, Drawable success, Drawable unsuccess) {
        mType = typ;
        successDrawable = success;
        successDrawable.setBounds(0, 0,
                successDrawable.getMinimumWidth(), successDrawable.getMinimumHeight());
        unsuccessDrawable = unsuccess;
        unsuccessDrawable.setBounds(0, 0,
                unsuccessDrawable.getMinimumWidth(), unsuccessDrawable.getMinimumHeight());
        mWarningMsg = new WarningMsg(typ);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        updateCleanable(s.toString().length(), true);
        if (s != null && s.length() > 0) {
            if (s.length() >= mMinLength && s.length() <= mMaxLength) {
                boolean isMatch = Check.getMatch(mType, s.toString(), userRegx);
                changeWarnStatus(!isMatch, mWarningMsg.getMsg());
//            if (isMatch) {
//                setCompoundDrawables(null, null, successDrawable, null);
//            } else {
//                setCompoundDrawables(null, null, unsuccessDrawable, null);
//            }
            } else {
                changeWarnStatus(true, mWarningMsg.getLengthMsg());
            }
        } else {
//            setCompoundDrawables(null, null, null, null);
            changeWarnStatus(false, mWarningMsg.getMsg());
        }
    }

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

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //可以獲得上下左右四個drawable,右側排第二。圖標沒有設置則為空。
        if (mRightDrawable != null && event.getAction() == MotionEvent.ACTION_UP) {
            //檢查點擊的位置是否是右側的刪除圖標
            //注意,使用getRwwX()是獲取相對屏幕的位置,getX()可能獲取相對父組件的位置
            int leftEdgeOfRightDrawable = getRight() - getPaddingRight()
                    - mRightDrawable.getBounds().width();
            if (event.getRawX() >= leftEdgeOfRightDrawable) {
                setText("");
            }
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void finalize() throws Throwable {
        mRightDrawable = null;
        super.finalize();
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        //更新狀態(tài),檢查是否顯示刪除按鈕
        updateCleanable(this.getText().length(), hasFocus);
    }

    /**
     * 當內(nèi)容不為空,而且獲得焦點,才顯示右側刪除按鈕
     * @param length
     * @param hasFocus
     */
    private void updateCleanable(int length, boolean hasFocus) {
        if (length > 0 && hasFocus) {
            setCompoundDrawablesRelativeWithIntrinsicBounds(mLeftDrawable, null, mRightDrawable, null);
        } else {
            setCompoundDrawablesRelativeWithIntrinsicBounds(mLeftDrawable, null, null, null);
        }
    }

    /**
     * 更新錯誤提示語狀態(tài)
     *
     * @param isShow 是否顯示提示語,true = 顯示
     * @param msg    提示語
     */
    private void changeWarnStatus(boolean isShow, String msg) {
        if (mWarnViewListener != null) {
            if (isShow) {
                mWarnViewListener.show(msg);
            } else {
                mWarnViewListener.hide();
            }
        }
    }
}

可能你們會問,為什么這邊是繼承TextInputEditText而不是EditText?其實這是為了全屏模式時依然在編輯器里展示hint.這點我在前言里面有提到,這邊再次說明下,大家也可以用EditText代替

AutoCheckEditTextClass

接下來就是如何使用了,我這邊專門寫了個類,用來處理TextInputLayout與EditText

/**
 * Created by caihan on 2017/1/22.
 * 專門處理EditText的類
 * 請使用widget_autocheck_et_layout.xml
 */
public class AutoCheckEditTextClass implements WarnViewStatus {
    private static final String TAG = "AutoCheckEditTextClass";

    private TextInputLayout mTextInputLayout;
    private AutoCheckEditText mAutoCheckEditText;

    public AutoCheckEditTextClass(TextInputLayout inputLayout, AutoCheckEditText editText) {
        mTextInputLayout = inputLayout;
        mAutoCheckEditText = editText;
    }

    /**
     * 設置正則校驗類型
     * @param typ
     * @return
     */
    public AutoCheckEditTextClass checkType(int typ) {
        mAutoCheckEditText.creatCheck(typ, this);
        return this;
    }

    /**
     * 設置最小判斷長度(一般不設置,默認0)
     * @param minLength
     * @return
     */
    public AutoCheckEditTextClass setMinLength(int minLength) {
        mAutoCheckEditText.setMinLength(minLength);
        return this;
    }

    /**
     * @param maxLength      設置最大長度的時候,一并設置計算器的最大字數(shù)限制
     * @param counterEnabled 計算器是否開啟
     * @return
     */
    public AutoCheckEditTextClass setMaxLength(int maxLength, boolean counterEnabled) {
        mTextInputLayout.setCounterMaxLength(maxLength);
        mTextInputLayout.setCounterEnabled(counterEnabled);
        mAutoCheckEditText.setMaxLength(maxLength);
        return this;
    }

    /**
     * @param maxLength 設置最大長度的時候,一并設置計算器的最大字數(shù)限制
     * @return
     */
    public AutoCheckEditTextClass setMaxLength(int maxLength) {
        mTextInputLayout.setCounterMaxLength(maxLength);
        mTextInputLayout.setCounterEnabled(false);
        mAutoCheckEditText.setMaxLength(maxLength);
        return this;
    }

    /**
     * TextInputLayout hint開關
     * 如果只想用EditText默認效果的話,請傳false,默認是true
     *
     * @param hintEnabled
     * @return
     */
    public AutoCheckEditTextClass setHintEnabled(boolean hintEnabled) {
        mTextInputLayout.setHintEnabled(hintEnabled);
        return this;
    }

    @Override
    public void show(String... msgs) {
        mTextInputLayout.setErrorEnabled(true);
        if (msgs.length > 0 && !StringUtils.isEmpty(msgs[0])) {
            mTextInputLayout.setError(msgs[0]);
        }
    }

    @Override
    public void hide() {
        mTextInputLayout.setErrorEnabled(false);
    }
}

界面調用

好了,模塊就介紹到這里,最后讓我們來看看界面上是如何調用的

Layout里

就一句話

<include layout="@layout/widget_autocheck_et_layout"/>

Acticity里

也是只有一個鏈路

AutoCheckEditTextClass editTextClass = new AutoCheckEditTextClass(mWidgetTextinputLayout,
                mWidgetEt)
                .checkType(EditTextType.TYPE_OF_MOBILE)
                .setMaxLength(11,true);

搞定收工!


感謝

感謝Blankj 提供的工具類AndroidUtilCode以及帶正則校驗的EditText

最后

一直想說找時間寫幾個Demo放到GitHub上,這樣比較方便伸手黨直接下載下來使用,不過一直沒時間,萬惡的老板開會說不能讓我太清閑,程序猿什么時候清閑過,大家評評理=.=

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容