Android Design新控件之TextInputLayout(文本输入布局)

谷歌在推出Android5.0的同时推出了全新的设计Material Design,谷歌为了给我们提供更加规范的MD设计风格的控件,在2015年IO大会上推出了Design支持包,Design常用的新控件包括:

  • TextInputLayout(文本输入布局)
  • TabLaout(选项卡布局)
  • Snackbar
  • FloatingActionButton(浮动按钮)
  • NavigationView(导航视图)
  • AppBarLayout(程序栏布局)
  • CoordinatorLayout(协作布局)
  • CollapsingToolbarLayout(折叠工具栏布局)

和往常一样,主要还是想总结一下我在学习过程中的一些笔记以及一些需要注意的地方。此文章已经同步到CSDN啦,欢迎访问我的博客

一、TextInputLayout的作用
TextInputLayout的作用是将EditText包裹起来,使得EditText的android:hint属性的值以浮动标签的形式显示出来,同时可以通过setErrorEnabled(boolean)设置是否显示一个错误信息和setError(CharSequence)来显示错误信息。

在xml文件中定义TextInputLayout:

<?xml version="1.0" encoding="utf-8"?>
<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="match_parent">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/text_input_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:counterEnabled="true"
        app:counterMaxLength="11"
        app:errorTextAppearance="@style/MyErrorStyle">

        <EditText
            android:id="@+id/et_phone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/txt_remind_phone"
            android:maxLength="11"
            android:phoneNumber="true"
            android:singleLine="true" />
    </android.support.design.widget.TextInputLayout>
</LinearLayout>

在java文件中设置错误信息:

package com.per.textinputlayout;

import android.app.Activity;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;

public class MainActivity extends Activity {
    private TextInputLayout textinputlayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textinputlayout= (TextInputLayout) findViewById(R.id.text_input_layout);

        textinputlayout.setErrorEnabled(true);
        textinputlayout.setError("请检查手机号码是否正确");
    }
}

这里写图片描述

其中app:errorTextAppearance="@style/MyErrorStyle"表示错误提示的样式,如果想更改错误提示的样式的话,也可以在style.xml文件里面,自定义一个style

 <style name="MyErrorStyle">
        <item name="android:textColor">#007810</item>
    </style>
属性名 相关方法 描述
app:counterEnabled setCounterEnabled(boolean) 设置是否显示一个计数器,布尔值
app:counterMaxLength setCounterMaxLength(int) 设置计数器的最大计数数值,整型
app:errorEnabled setErrorEnabled(boolean) 设置是否显示一个错误信息,布尔值
app:hintAnimationEnabled setHintAnimationEnabled(boolean) 设置是否要显示输入状态时候的动画效果,布尔值
app:hintEnabled setHintEnabled(boolean) 设置是否要用这个浮动标签的功能,布尔值
app:hintTextAppearance setHintTextAppearance(int) 设置提示文字的样式(注意这里是运行了动画效果之后的样式)

二、TextInputLayout常用属性

属性名 相关方法 描述
app:counterEnabled setCounterEnabled(boolean) 设置是否显示一个计数器,布尔值
app:counterMaxLength setCounterMaxLength(int) 设置计数器的最大计数数值,整型
app:errorEnabled setErrorEnabled(boolean) 设置是否显示一个错误信息,布尔值
app:hintAnimationEnabled setHintAnimationEnabled(boolean) 设置是否要显示输入状态时候的动画效果,布尔值
app:hintEnabled setHintEnabled(boolean) 设置是否要用这个浮动标签的功能,布尔值
app:hintTextAppearance setHintTextAppearance(int) 设置提示文字的样式(注意这里是运行了动画效果之后的样式)

这里写了一个简单的登录页面,仅供参考,效果图如下:


这里写图片描述

OtherActivity.class

package com.per.textinputlayout;

import android.app.Activity;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Created by lijuan on 2016/8/21.
 */
public class OtherActivity extends Activity implements View.OnClickListener {
    private TextInputLayout mLayoutPhone, mLayoutPwd, mLayoutEmail;
    private EditText mEtPhone, mEtPwd, mEtEmail;
    private Button mBtnLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other);
        initView();
    }

    private void initView() {
        mLayoutPhone = (TextInputLayout) findViewById(R.id.layout_phone);
        mLayoutPwd = (TextInputLayout) findViewById(R.id.layout_pwd);
        mLayoutEmail = (TextInputLayout) findViewById(R.id.layout_email);

        mEtPhone = (EditText) findViewById(R.id.et_phone);
        mEtPwd = (EditText) findViewById(R.id.et_pwd);
        mEtEmail = (EditText) findViewById(R.id.et_email);

        mBtnLogin = (Button) findViewById(R.id.login);

        //设置监听事件
        mBtnLogin.setOnClickListener(this);
        mEtPhone.addTextChangedListener(new MyTextWatcher(mEtPhone));
        mEtPwd.addTextChangedListener(new MyTextWatcher(mEtPwd));
        mEtEmail.addTextChangedListener(new MyTextWatcher(mEtEmail));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login:
                Login();
                break;
            default:
                break;
        }
    }

    /**
     * 登录
     */
    private void Login() {
        if (!isNameValid()) {
            showMessage(getString(R.string.error_phone));
            return;
        }
        if (!isPasswordValid()) {
            showMessage(getString(R.string.error_pwd));
            return;
        }
        if (!isEmailValid()) {
            showMessage(getString(R.string.error_email));
            return;
        }
        showMessage(getString(R.string.login_success));
    }

    /**
     * 检查输入的手机号码是否为空以及格式是否正确
     *
     * @return
     */
    public boolean isNameValid() {
        String phone = mEtPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone) || !RegularUtils.isPhone(phone)) {
            mLayoutPhone.setErrorEnabled(true);
            mLayoutPhone.setError(getString(R.string.error_phone));
            mEtPhone.requestFocus();
            return false;
        }
        mLayoutPhone.setErrorEnabled(false);
        return true;
    }

    /**
     * 检查输入的密码是否为空
     *
     * @return
     */
    public boolean isPasswordValid() {
        String pwd = mEtPwd.getText().toString().trim();
        if (TextUtils.isEmpty(pwd)) {
            mLayoutPwd.setErrorEnabled(true);
            mLayoutPwd.setError(getResources().getString(R.string.error_pwd));
            mEtPwd.requestFocus();
            return false;
        }
        mLayoutPwd.setErrorEnabled(false);
        return true;
    }

    /**
     * 检查输入的邮箱是否为空以及格式是否正确
     *
     * @return
     */
    public boolean isEmailValid() {
        String email = mEtEmail.getText().toString().trim();
        if (TextUtils.isEmpty(email) || !RegularUtils.isEmail(email)) {
            mLayoutEmail.setErrorEnabled(true);
            mLayoutEmail.setError(getString(R.string.error_email));
            mLayoutEmail.requestFocus();
            return false;
        }
        mLayoutEmail.setErrorEnabled(false);
        return true;
    }

    //动态监听输入过程
    private class MyTextWatcher implements TextWatcher {

        private View view;

        private MyTextWatcher(View view) {
            this.view = view;
        }

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

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

        @Override
        public void afterTextChanged(Editable s) {
            switch (view.getId()) {
                case R.id.et_phone:
                    isNameValid();
                    break;
                case R.id.et_pwd:
                    isPasswordValid();
                    break;
                case R.id.et_email:
                    isEmailValid();
                    break;
            }
        }
    }

    private void showMessage(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

}

这里还涉及到了一个检测手机号码,邮箱等是否有效的一个工具类:RegularUtils.class

package com.per.textinputlayout;

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

/**
 * 检测手机号码,邮箱等是否有效
 * Created by xiaolijuan on 2016/8/21.
 */
public class RegularUtils {
    /**
     * 要更加准确的匹配手机号码只匹配11位数字是不够的,比如说就没有以144开始的号码段,
     * 故先要整清楚现在已经开放了多少个号码段,国家号码段分配如下:
     * 移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
     * 联通:130、131、132、152、155、156、185、186   电信:133、153、180、189、(1349卫通)
     */
    public static boolean isPhone(String param) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher m = p.matcher(param);
        return m.matches();
    }

    /**
     * 判断email格式是否正确
     */
    public static boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }
}

activity_other.xml

<?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"
    android:layout_width="match_parent"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    android:layout_height="match_parent">

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

        <android.support.design.widget.TextInputLayout
            android:id="@+id/layout_phone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:counterEnabled="true"
            app:counterMaxLength="11"
            app:errorTextAppearance="@style/MyErrorStyle">

            <EditText
                android:phoneNumber="true"
                android:id="@+id/et_phone"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/txt_remind_phone"
                android:maxLength="11"
                android:singleLine="true" />
        </android.support.design.widget.TextInputLayout>

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

            <EditText
                android:id="@+id/et_pwd"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/txt_remind_pwd"
                android:inputType="textPassword"
                android:maxLength="6"
                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:errorTextAppearance="@style/MyErrorStyle">

            <EditText
                android:id="@+id/et_email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/txt_remind_email"
                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_margin="25dp"
            android:background="@color/colorPrimary"
            android:text="@string/txt_login"
            android:textColor="@android:color/white"
            android:textSize="18sp"
            android:textStyle="bold" />
    </LinearLayout>
</RelativeLayout>

好了,本篇文章已经全部写完了,存在总结不到位的地方还望指导,感谢_

参考资料:
一个Activity掌握Design新控件

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,110评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,443评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,474评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,881评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,902评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,698评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,418评论 3 419
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,332评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,796评论 1 316
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,968评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,110评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,792评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,455评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,003评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,130评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,348评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,047评论 2 355

推荐阅读更多精彩内容