我的 Material Design EditText, 实现删除功能

3,002 阅读10分钟

我的Material Design EditText,实现删除功能

本文原创,转载请注明出处。欢迎关注我的 简书

前言:

Material Design推出了一种优秀的文本输入框形式——当用户点击空内容的文本输入框时,原本位于输入框内的提示语会经由一个动画浮动至输入框上方,文本颜色同时变成强调色,明确显示此时该组件获得焦点
为了让开发者更加方便地实现这种效果Google推出了TextInputLayout组件,里面放置一个EditText或者TextInputEditText,可以轻松实现

添加依赖

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

TextInputLayout常用属性以及用法

布局中的名称 参数类型 代码中的方法名称 注解
counterEnabled boolean setCounterEnabled(boolean) 用于设置字符计数器的开启或关闭
counterMaxLength int setCounterMaxLength(int) 设置字符计数器的最大长度。(仅用于设置计数器最大值,并不影响文本实际能输入的最大长度)
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,字体颜色,字体大小等,可引用系统自带的也可以自定义。若要使用请统一使用,以保证APP体验的统一性。
passwordToggleEnabled boolean setPasswordVisibilityToggleEnabled(boolean) 控制密码可见开关是否启用。设为false则该功能不启用,密码输入框右侧也没有控制密码可见与否的开关。
passwordToggleDrawable Drawable setPasswordVisibilityToggleDrawable(Drawable) 设置密码可见开关的图标。通常我们会在不同的情况下设定不同的图标,可通过自定义一个selector,根据“state_checked”属性来控制图标的切换。
passwordToggleTint Color setPasswordVisibilityToggleTintList(ColorStateList) 控制密码可见开关图标的颜色。在开启或关闭的状态下我们可以设定不同的颜色,可通过自定义一个color的selector,根据“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"//设置是否可以使用hint属性,默认是true
    app:hintAnimationEnabled="true"//设置是否可以使用动画,默认是true
    app:hintTextAppearance="@style/hintAppearance"//设置hint的文本属性,改变hint文字的大小颜色等属性
    app:counterEnabled="true"//设置是否可以开启计数器,默认是false
    app:counterOverflowTextAppearance="@style/counterOverflowTextAppearance"//设置计算器越位后的文字颜色和大小
    app:counterTextAppearance="@style/hintAppearance"//设置正常情况下的计数器文字颜色和大小
    app:counterMaxLength="11"//设置计算器的最大字数限制
    app:errorEnabled="true"//是否允许错误提示,默认是true
    app:errorTextAppearance="@style/errorAppearance"//错误提示的文字大小和颜色
    app:passwordToggleEnabled="true"//设置是否显示密码眼睛,默认是false
    app:passwordToggleDrawable="@mipmap/ic_launcher"//自定义眼睛图标
    app:passwordToggleTint="@color/colorAccent"//给眼睛着色
    app:passwordToggleTintMode="multiply"//选择着色模式,与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>

<!--超出计数最大长度,浮动标签,下划线,计数文字都会改变颜色-->
<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.
 * 警告语显示监听
 */
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 是否符合网址格式
     */
    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这个类实现了删除按钮正则判断
注解都写的比较详细,就不重复说明了,如果有不懂的地方再问我

/**
 * 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 错误提示语状态监听
     */
    public void creatCheck(int typ, WarnViewStatus warnViewStatus) {
        this.mType = typ;
        mWarningMsg = new WarningMsg(typ);
        mWarnViewListener = warnViewStatus;
    }

    /**
     * 设置判断的长度区间
     *
     * @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) {
        //更新状态,检查是否显示删除按钮
        updateCleanable(this.getText().length(), hasFocus);
    }

    /**
     * 当内容不为空,而且获得焦点,才显示右侧删除按钮
     * @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);
        }
    }

    /**
     * 更新错误提示语状态
     *
     * @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      设置最大长度的时候,一并设置计算器的最大字数限制
     * @param counterEnabled 计算器是否开启
     * @return
     */
    public AutoCheckEditTextClass setMaxLength(int maxLength, boolean counterEnabled) {
        mTextInputLayout.setCounterMaxLength(maxLength);
        mTextInputLayout.setCounterEnabled(counterEnabled);
        mAutoCheckEditText.setMaxLength(maxLength);
        return this;
    }

    /**
     * @param maxLength 设置最大长度的时候,一并设置计算器的最大字数限制
     * @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上,这样比较方便伸手党直接下载下来使用,不过一直没时间,万恶的老板开会说不能让我太清闲,程序猿什么时候清闲过,大家评评理=.=