从登录界面学习TextInputLayout

前言

源码传送门javascript

在 Material Design出现以前,若是咱们想写一个登录界面是否是通常都写两组TextView,EditText及一个Button,若是你想在帐号和密码后面加一个计数的功能,又须要加控件而且要本身实现计数,或者在密码框后面加个相似眼睛的密码显示开关,或者你想加一个帐号或者密码输入无效或者错误的提醒,通常是显示一个Toast或者使用EditText的setError设置,不过体验并非太好,等等这些麻烦的的处理在Material Design TextInputLayout出现后获得了极大改善,咱们能够作最少的事达到最好的效果,今天的这篇文章就是经过一个登录界面来学习TextInputLayout的API重要方法及其使用。先来一张效果图html

这里写图片描述

添加依赖

TextInputLayout是在Material Design中的,因此咱们须要在gradle 文件配置java

dependencies {
    compile 'com.android.support:appcompat-v7:24.2.0'
    compile 'com.android.support:design:24.2.0'
}复制代码

使用

TextInputLayout官方文档API中描述它是一种新的继承自LinearLayout的布局,使用时只能包含一个EditText或其子类的控件,该布局能够经过设置hint和Error显示浮动标签。接下咱们看看布局文件android

<LinearLayout
            android:id="@+id/account_login_form"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <android.support.design.widget.TextInputLayout
                android:id="@+id/accountinput"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/prompt_account"
                >

            <EditText
                android:id="@+id/account"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text=""
                android:inputType="phone"
                android:singleLine="true"/>

            </android.support.design.widget.TextInputLayout>
            <android.support.design.widget.TextInputLayout
                android:id="@+id/passwordinput"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/prompt_password"
                >

            <EditText
                android:id="@+id/password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:singleLine="true"/>

            </android.support.design.widget.TextInputLayout>

            <Button
                android:id="@+id/account_sign_in_button"
                style="?android:textAppearanceSmall"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:background="@drawable/login_btn"
                android:textColor="@color/btninvalid"
                android:text="@string/action_sign_in"
                android:textStyle="bold"/>

        </LinearLayout>复制代码

使用其实很简单,只须要一个TextInputLayout(须要全路径)容器并在其中加一个EditText(或子类),须要注意的是一个TextInputLayout有且只能对应一个EditText。在TextInputLayout加入android:hint="帐号"就能够显示一个浮动标签了,效果图如上,还能够经过下面代码将浮动标签关闭,若是关闭的话,设置hint也就没有效果了,默认是开启的。git

app:hintEnabled="false"复制代码

对于android:hint="帐号"属性在TextInputLayout或者在EditText中设置均可以达到咱们浮动标签的效果,可是不能在二者中同时使用设置hint,当二者同时使用时没有获取焦点时都会显示hint(两个hint重叠显示),获取焦点时TextInputLayout设置的hint会成为悬浮标签,可是此时EditText设置的hint不会消失,有输入内容时才会消失,具体缘由能够本身阅读源码查看,代码很少,很容易看出来。对于浮动标签显示隐藏切换有一个过渡动画,能够经过 app:hintAnimationEnabled="boolean"设置。github

若是咱们此时想在帐号那一栏后面加个字数统计,例如通常状况咱们的帐号是固定位数的,若是使用手机号做为咱们的登陆帐号,此时咱们加一个统计输入长度能够提示用户固然也能够超过位数时限制其输入,咱们只须要在TextInputLayout加入app

app:counterEnabled="true"复制代码

默认是关闭的,固然咱们能够设置一个输入的最大长度,此处设置11.ide

app:counterMaxLength="11"复制代码

当咱们设置输入的最大技术长度11时并非到达11后不能再输入计数,而是会以一种颜色提示用户强调超过设置长度。布局

TextInputLayout提供了设置错误提醒的功能,在此篇文章中咱们用手机号及密码至少6位作判断,学习

if (TextUtils.isEmpty(account)||!isAccountValid(account)) {
            accountinput.setError(getString(R.string.error_invalid_account));
       }

   if (TextUtils.isEmpty(password)||!isPasswordValid(password)) {
            passwordinput.setError(getString(R.string.error_invalid_password));
        }
   private boolean isAccountValid(String name) {
        //TODO: Replace this with your own logic
        Pattern pattern= Pattern.compile("^(13[0-9]|14[5|7]|15\\d|17[6|7]|18[\\d])\\d{8}$");
        return pattern.matcher(name).matches();
        }

    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() > 6;
    }复制代码

当咱们输入不符合规则,设置错误,显示效果以下,

这里写图片描述

对于设置错误,能够经过app:errorEnabled="boolean"或者代码accountinput.setEnabled(boolean);将其打开或者关闭,当经过accountinput.setError()设置错误时源码中默认调用setEnabled(true)打开,无需本身再次调用,还有一个注意的地方设置后不会自动取消,须要本身调用accountinput.setError(null);取消错误提示。例如在上面图示提示错误后,咱们在编辑该EditText时须要取消错误提示,那么咱们能够经过addTextChangedListener监听,代码以下

mAccountView.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) {
                if(accountinput.getError()!=null){
                    accountinput.setError(null);
                }
            }
        });复制代码

当咱们编辑时回调执行,咱们经过getError获取设置的错误信息,若是设置的有内容则返回设置的字符,默认为null。

对于输入密码的空间咱们经过TextInputLayout中EditText 的android:inputType="textPassword"设置输入密码,此时咱们能够在右侧看到一个眼睛的密码开关实现将密码显示或隐藏。若是咱们不想显示这个眼睛图标能够在TextInputLayout中加入

app:passwordToggleEnabled="false"复制代码

此时就看不到眼睛的图标,密码也不在隐藏,当咱们想将眼睛的图标设置为咱们本身设计的图标时,能够经过下面代码设置

app:passwordToggleDrawable="@drawable/common_full_open_on_phone"复制代码

咱们还能够经过passwordToggleTint给图标设置着色而且经过passwordToggleTintMode设置对应模式,达到更好看的效果。
是否是很简单,这些功能要在以前布局确定须要一大堆代码的,而如今很简单,只要几行代码。

自定义EditText下划线样式

这里写图片描述

默认状况下EditText的下划线是灰色的,当获取焦点时颜色是colorAccent,如上图,若是咱们想自定义,能够给TextInputLayout加一个theme,以下代码

android:theme="@style/customLineColor"复制代码

customLineColor样式为colorControlNormal为没有获取焦点时的颜色,colorControlActivated为获取焦点时的颜色,这样就能够设置咱们想要的颜色了。

<style name="customLineColor" parent="Theme.AppCompat.Light">
    <item name="colorControlNormal">@color/colorAccent</item>
     <item name="colorControlActivated">@color/drawerTextColor</item>
    </style>复制代码

自定义浮动标签

默认状况下浮动标签的颜色也是colorAccent,咱们能够经过hintTextAppearance设置浮动标签字体样式,如
app:hintTextAppearance="@style/hintAppearance",

<style name="hintAppearance" parent="TextAppearance.AppCompat">
        <item name="android:textSize">14sp</item>
        <item name="android:textColor">@color/colorPrimary</item>
    </style>复制代码

自定义错误提示信息

app:errorTextAppearance="@style/errorAppearance"

<style name="errorAppearance" parent="TextAppearance.AppCompat">
        <item name="android:textSize">14sp</item>
        <item name="android:textColor">@color/red</item>
    </style>复制代码

自定义超出计数最大长度样式

app:counterOverflowTextAppearance="@style/counterOverflowTextAppearance"

<style name="counterOverflowTextAppearance" parent="TextAppearance.AppCompat">
        <item name="android:textSize">14sp</item>
        <item name="android:textColor">@color/red</item>
    </style>复制代码

监控虚拟键盘

经过上面的介绍,咱们将TextInputLayout的使用及经常使用的设置都已经都介绍了,既然文章名字是登陆界面,下面简单介绍一下其余一些比较多登陆界面的一些实现。如当焦点在帐户上,咱们输入完成后直接点击虚拟键盘上的下一项时焦点直接跳到密码项,密码输入完成,直接能够点击虚拟键盘的肯定就能够登陆,该怎么实现呢。以下
在帐号的EditText中加入

android:imeActionId="@+id/password"
                android:imeOptions="actionNext"复制代码

在密码的EditText中加入

android:imeActionId="@+id/account_sign_in_button"
                android:imeOptions="actionDone"复制代码
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if ( id == EditorInfo.IME_ACTION_DONE) {
                    InputMethodManager inputMethodManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    //inputMethodManager.showSoftInput(getWindow().getDecorView(),InputMethodManager.SHOW_FORCED);//显示
                    inputMethodManager.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(),InputMethodManager.RESULT_UNCHANGED_SHOWN);
                    //attemptLogin();
                    startLogin();
                    return true;
                }
                return false;
            }
        });复制代码

动态监测登陆按钮

在支付宝中,当帐户名或者密码有没填的项,登陆按钮就是不可点击的,并经过样式给用户反馈是否是能够点击。这个也很简单,只须要给两个EditText设置addTextChangedListener监听,监听两个控件只有有没填项就将登陆按钮设置为不能够点击,不然能够点击,核心代码

if (account.equals("")||password.equals("")){
                    mAccountSignInButton.setClickable(false);
                    mAccountSignInButton.setTextColor(getResources().getColor(R.color.btninvalid));
                }else{
                    mAccountSignInButton.setClickable(true);
                    mAccountSignInButton.setTextColor(getResources().getColor(R.color.white));
                }复制代码

#多帐号自动提示
AutoCompleteTextView是EditText的子类,能够实现自动提示功能该控件有一个setAdapter方法,能够监测咱们输入的内容在传入的适配器中有数据时会自动弹出下拉提示,在文章开始效果图已经展现,代码简单实现

private  String[] accounts = { "18236593333", "13463373657", "18235784765", "18234637686" };

        ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,accounts);
        mAccountView.setAdapter(arrayAdapter);//输入至少两个字符才会提示复制代码

Ok,到这里本篇文章就结束了,有问题欢迎留言指出,Have a wonderful day .

相关文章
相关标签/搜索