Android开发——Material Design系列之TextInputLayout

0. 前言  html

TextInputLayout 继承于 LinearLayout,专门用来包裹 EditTextEditText的子类,当用户进行输入动做的时候咱们设置的android:hint 属性值会做为提示以动画的形式运动到输入框左上角,错误信息也显示在输入框的下方。有些输入验证是在后台作得,产生错误后再反馈给前台,这样很是耗时并且用户体验差。TextInputLayout则完美的解决了这个问题,达到了很好的用户体验效果。java

先看一下效果图,后面慢慢进行实现的介绍。android



1.  TextInputLayout的使用正则表达式

dependencies {
    //…
    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.android.support:design:25.0.0
}

首先添加supportdesign依赖包,版本号最好和v7包一致。app


2.  布局文件函数

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    tools:context="com.seucalvin.textinputlayout.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="65dp"
        android:orientation="vertical">

        <android.support.design.widget.TextInputLayout
            android:id="@+id/layout_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:counterEnabled="true"
            app:counterMaxLength="6">
            <!--app:counterOverflowTextAppearance="@style/MyOverflowText"-->
            <!--app:errorTextAppearance="@style/MyErrorStyle">-->

            <EditText
                android:id="@+id/input_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/EnterName"
                android:singleLine="true" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/layout_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:counterEnabled="true"
            app:counterMaxLength="6">
            <!--app:counterOverflowTextAppearance="@style/MyOverflowText"-->
            <!--app:errorTextAppearance="@style/MyErrorStyle">-->

            <EditText
                android:id="@+id/input_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/EnterPassWord"
                android:inputType="textPassword"
                android:singleLine="true" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/layout_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <!--app:counterOverflowTextAppearance="@style/MyOverflowText"-->
            <!--app:errorTextAppearance="@style/MyErrorStyle">-->

            <EditText
                android:id="@+id/input_email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/EnterEmail"
                android:inputType="textEmailAddress"
                />
        </android.support.design.widget.TextInputLayout>

        <Button
            android:id="@+id/login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="50dp"
            android:background="@color/colorPrimary"
            android:text="@string/login"
            android:textColor="#ffffff"
            android:textSize="20sp"
            android:textStyle="bold" />
    </LinearLayout>
</RelativeLayout>

布局很简单,一个用户名输入框和一个密码框,再加上一个email输入框和登录按钮。工具

这里在用户名和密码输入框里所在的TextInputLayout配置了app:counterEnabled=true”属性便可进行效果图中的字数统计功能。固然,你也能够指定最大输入的字符数,这里使用app:counterMaxLength=6指定了最多输入6个字符。最后就是app:counterOverflowTextAppearanceapp:errorTextAppearance两个属性,这里我都注释掉了,即便用的是系统默认的效果,二者均可以经过指定style进行自定义效果,前者为当输入字符超过限定个数时EditText控件的总体显示样式,好比能够自定义输入框的颜色的改变,注意若是要自定义styleparent属性要是TextAppearance.AppCompat.Small,后者即显示错误提示文字(输入框左下方)的属性,好比修改其颜色啊等等。布局

EditTexthint属性指定的是飘在输入框左上角的文字,那么左下角的错误提示文字是如何设置内容以及出现时机的呢?动画


3. 代码逻辑url

首先确定要响应EditText的输入事件,这样才能实时地检测是否输入有误。

input_name.addTextChangedListener(newMyTextWatcher(input_name));
这里 MyTextWatcher 实现了 TextWatcher 接口 ,并重写了该接口中的 afterTextChanged() 方法 ,在该方法中经过判断 MyTextWatcher() 构造函数中传来的控件 id ,来 switch 到底进行哪一个输入框的逻辑判断,这里以 邮件输入框 的逻辑举例介绍:

String email = input_email.getText().toString().trim();
if (TextUtils.isEmpty(email) || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
    layout_email.setErrorEnabled(true);
    layout_email.setError(getString(R.string.error_email));
    layout_email.requestFocus();
}
layout_email.setErrorEnabled(false);

该逻辑在输入事件发生后实时回调,当检测到邮箱输入框为空或者邮箱格式有误时,会调用layout_eamil.setError()使所在的TextInputLayout左下角显示错误提示信息。不然传入false隐藏错误信息。这样就完成了效果图中的效果。


4. TextInputEditText

官方的实例中,TextInputLayout包裹的并非EditText,而是TextInputEditText,它是EditText的子类,那么它和EditText有什么区别呢,官方给出的解释是,当你的输入框太大的时候,以下图所示:



点击输入框会进入全屏编辑模式,以下图所示,若是你使用的是EditText,则以下图所示:



而若是你使用的是TextInputEditText,则会在全屏编辑模式下依然显示出hint属性值,以下图所示:



5.  正则表达式工具类

Android开发中常常在登陆逻辑中使用正则表达式校验邮箱、手机号、密码、身份证号码等信息,特地找到了一个工具类方便须要的同窗使用。

/**
 * 校验器:利用正则表达式校验邮箱、手机号等
 * @author Mr.duan
 */
public class Validator {
    /**
     * 正则表达式:验证用户名(不包含中文和特殊字符)若是用户名使用手机号码或邮箱 则结合手机号验证和邮箱验证
     */
    public static final String REGEX_USERNAME = "^[a-zA-Z]\\w{5,17}$";

    /**
     * 正则表达式:验证密码(不包含特殊字符)
     */
    public static final String REGEX_PASSWORD = "^[a-zA-Z0-9]{6,16}$";

    /**
     * 正则表达式:验证手机号
     */
    public static final String REGEX_MOBILE = "^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$";

    /**
     * 正则表达式:验证邮箱
     */
    public static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";

    /**
     * 正则表达式:验证汉字(1-9个汉字)  {1,9} 自定义区间
     */
    public static final String REGEX_CHINESE = "^[\u4e00-\u9fa5]{1,9}$";

    /**
     * 正则表达式:验证身份证
     */
    public static final String REGEX_ID_CARD = "(^\\d{15}$)|(^\\d{17}([0-9]|X)$)";

    /**
     * 正则表达式:验证URL
     */
    public static final String REGEX_URL = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";

    /**
     * 正则表达式:验证IP地址 
     */
    public static final String REGEX_IP_ADDR = "(2[5][0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})";

    /**
     * 校验用户名
     * @param username
     * @return 校验经过返回true,不然返回false
     */
    public static boolean isUserName(String username) {
        return Pattern.matches(REGEX_USERNAME, username);
    }

    /**
     * 校验密码
     * @param password
     * @return 校验经过返回true,不然返回false
     */
    public static boolean isPassword(String password) {
        return Pattern.matches(REGEX_PASSWORD, password);
    }

    /**
     * 校验手机号
     * @param mobile
     * @return 校验经过返回true,不然返回false
     */
    public static boolean isMobile(String mobile) {
        return Pattern.matches(REGEX_MOBILE, mobile);
    }

    /**
     * 校验邮箱
     * @param email
     * @return 校验经过返回true,不然返回false
     */
    public static boolean isEmail(String email) {
        return Pattern.matches(REGEX_EMAIL, email);
    }

    /**
     * 校验汉字
     * @param chinese
     * @return 校验经过返回true,不然返回false
     */
    public static boolean isChinese(String chinese) {
        return Pattern.matches(REGEX_CHINESE, chinese);
    }

    /**
     * 校验身份证
     * @param idCard
     * @return 校验经过返回true,不然返回false
     */
    public static boolean isIDCard(String idCard) {
        return Pattern.matches(REGEX_ID_CARD, idCard);
    }

    /**
     * 校验URL
     * @param url
     * @return 校验经过返回true,不然返回false
     */
    public static boolean isUrl(String url) {
        return Pattern.matches(REGEX_URL, url);
    }

    /**
     * 校验IP地址
     * @param ipAddress
     * @return
     */
    public static boolean isIPAddress(String ipAddress) {
        return Pattern.matches(REGEX_IP_ADDR, ipAddress);
    }

}