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

谷歌在推出Android5.0的同时推出了全新的设计Material Design,谷歌为了给咱们提供更加规范的MD设计风格的控件,在2015年IO大会上推出了8 个新的组件,同时向后兼容,新推出的这几个官方组件可能是在 GitHub 上很火热的一些项目:css

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

    和往常同样,主要仍是想总结一下我在学习过程当中的一些笔记以及一些须要注意的地方。android

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

在xml文件中定义TextInputLayout:app

<?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文件中设置错误信息:ide

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文件里面,自定义一个stylesvg

<style name="MyErrorStyle"> <item name="android:textColor">#007810</item> </style>

2、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开始的号码段, * 故先要整清楚如今已经开放了多少个号码段,国家号码段分配以下: * 移动:13四、13五、13六、13七、13八、13九、150、15一、157(TD)、15八、15九、18七、188 * 联通:130、13一、13二、15二、15五、15六、18五、186   电信:13三、15三、180、18九、(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新控件