一、概述
TextInputLayout通过对EditText进行包装,扩展了EditText的功能,今天,我们就来介绍一下和TextInputLayout相关的知识:
- 输入检查
- 输入计数
- 密码隐藏
二、TextInputLayout
2.1 基本用法
- 首先,导入
TextInputLayout的依赖包:
compile 'com.android.support:design:25.3.1'
- 之后,我们需要将
TextInputLayout作为EditText的父容器以实现相关的功能,例如下面这样,我们的布局中有两个EditText,都使用TextInputLayout把它们包裹起来。
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"/>
</android.support.design.widget.TextInputLayout>
</LinearLayout>
当EditText获得焦点的时候,android:hint所指定的字符串会以高亮的颜色显示在EditText的上方,而当EditText失去焦点时,hint会以灰显的方式显示在EditText中,这就是TextInputLayout最基本的使用,它让我们在输入的过程当中仍然可以获得当前EditText所关联的提示。
2.2 输入检查
除了在EditText上面的提示之外,TextInputLayout还支持在EditText下方显示提示,这种一般用于用户在输入过程中,输入了不符合要求的文本,用来给予用户错误提示。
private void checkError() {
mPasswordEditText.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) {
int len = s.length();
if (len > MAX_PASSWORD_LEN) {
mPasswordTextInput.setError("Max Password len is " + MAX_PASSWORD_LEN);
} else {
mPasswordTextInput.setErrorEnabled(false);
}
}
});
}
效果如下图所示:
EditText的输入,然后在某个条件被触发时,调用TextInputLayout的setError方法,以提示用户,与setError相关的方法有:
public void setError(@Nullable final CharSequence error)设置错误提示的文字,它会被显示在EditText的下方public void setErrorTextAppearance(@StyleRes int resId)设置错误提示的文字颜色和大小public void setErrorEnabled(boolean enabled)设置错误提示是否可用
2.3 输入计数
TextInputLayout还支持对于输入框内字符的实时统计,并在字符数超过阈值之后,改变输入框及提示文字的颜色。
private void checkCount() {
mPasswordTextInput.setCounterEnabled(true);
mPasswordTextInput.setCounterMaxLength(MAX_PASSWORD_LEN);
}
public void setCounterEnabled(boolean enabled)设置计数功能是否可用public void setCounterMaxLength(int maxLength)设置计数功能的阈值
2.4 输入时隐藏密码
相信大家都有见到过这样的输入框,在输入框的右边有一个开关,可以让用户来决定输入过程中的字符是否隐藏(以*号显示),TextInputLayout也提供了这样的功能:
EditText的inputType为textPassword/textWebPassword/numberPassword时,通过下面的设置:
mPasswordTextInput.setPasswordVisibilityToggleEnabled(true);
更多文章,欢迎访问我的 Android 知识梳理系列:
- Android 知识梳理目录:www.jianshu.com/p/fd82d1899…
- 个人主页:lizejun.cn
- 个人知识总结目录:lizejun.cn/categories/