Android Material Design控件学习(三)——使用TextInputLayout实现酷市场登录效果

前言

前两次,我们学习了

今天我们继续MD控件的学习和使用。在学习之前,我们先来看一下酷市场的登录效果。

实现这种效果的正是我们今天的主角——TextInputLayout。

学习

不管学习什么,首先看它的官方文档。这是最权威,最高效的学习途径。

文档地址:http://developer.android.com/reference/android/support/design/widget/TextInputLayout.html

可以看到,TextInputLayout继承自LinearLayout。一般将EditText和它的子类包含在内,以便用户在输入文本时,且当提示文本被隐藏时显示一个浮动的标签。

也支持通过setErrorEnabled(boolean)和setError(CharSequence)方法来显示错误提示。

用法

TextInputLayout使用起来非常简单,两部搞定

  • 1.编写XML布局文件,将EditText包含在内即可。
 <android.support.design.widget.TextInputLayout
            android:id="@+id/textInputLayoutName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="30dp">

            <EditText
                android:id="@+id/editTextName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/hint_name"
                android:textColorHint="@color/colorGray"
                />
        </android.support.design.widget.TextInputLayout>
  • 2.编写逻辑代码
    本来不需要这一步的,因为这控件存在一个bug,当清空之前输错的内容后,提示错误的红色文字并不会消失。

我在Google和StackOverFlow上找了很久,这貌似是Google的bug。可参考 https://code.google.com/p/android/issues/detail?id=190355

为了解决这个bug,就需要我们监听EditText的输入变化了,具体处理看代码。

  mEditTextName.addTextChangedListener(new TextWatcher() {
            @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) {
                checkName(s.toString(),false);
            }
        });
/**
 *若用户名为空且用户是想登录,提示错误,返回false。不为空,错误设为null
 */
 private boolean checkName(CharSequence name,boolean isLogin) {
        if(TextUtils.isEmpty(name)) {
            if(isLogin) {
                mTextInputLayoutName.setError(getString(R.string.error_login_empty));
                return false;
            }
        }else{
            mTextInputLayoutName.setError(null);
        }
        return true;
    }

实现效果:

具体代码我上传到Github了,https://github.com/JohnTsaiAndroid/CoolMarket

欢迎star&fork

posted @ 2016-02-03 23:30  onerepublic  阅读(2196)  评论(0编辑  收藏  举报