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

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

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

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

一、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>

二、TextInputLayout常用属性

属性名相关方法描述
app:counterEnabledsetCounterEnabled(boolean)设置是否显示一个计数器,布尔值
app:counterMaxLengthsetCounterMaxLength(int)设置计数器的最大计数数值,整型
app:errorEnabledsetErrorEnabled(boolean)设置是否显示一个错误信息,布尔值
app:hintAnimationEnabledsetHintAnimationEnabled(boolean)设置是否要显示输入状态时候的动画效果,布尔值
app:hintEnabledsetHintEnabled(boolean)设置是否要用这个浮动标签的功能,布尔值
app:hintTextAppearancesetHintTextAppearance(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新控件

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值