您的位置:首页 > 移动开发 > Android开发

android EditText长度监听

2017-07-21 17:40 399 查看

EditText长度监听

       EditText长度监听使用很广泛,例如qq的密码。本文介绍两种展示方式,也不能说两种,另一种只是在外层包了design包下的TextInputLayout。废话不多说,直接来代码。

1、添加design依赖
compile 'com.android.support:design:24.2.1'


2、布局
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/dlRoot"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Snackbar"
android:visibility="gone" />

<android.support.design.widget.TextInputLayout
android:id="@+id/til"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="please input" />

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

<EditText
android:id="@+id/et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="please input" />

</LinearLayout>

</android.support.v4.widget.DrawerLayout>

3、MainActivity
外层包了TextInputLayout的EditText
editText.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 (s.length() > 10) {
textInputLayout.setErrorEnabled(true);
textInputLayout.setError("输入超长");
} else {
textInputLayout.setErrorEnabled(false);
}
}
});


普通的EditText
et.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 (s.length() > 10)et.setError("输入超长");
}
});


       两个监听不同之处就是外层包了TextInputLayout判断的时候是否允许显示超长提示。到此为止,还不知道外层包了东西的EditText有啥不同之处。看下面的图,具体分析。上面的EditText有包裹的,下面的是普通的。

1、没有输入的时候看不出啥效果。感觉都一样



2、通过图一和图二有个问题显而易见,那就是获得焦点的时候AET(后面都用AET和BET区分) please input的位置到上面去了,颜色也发生了变化。



3、图3,4两个EditText的区别完全体现出来了。超长提示完全不一样,你更喜欢哪一种呢?





4、都未超长的时候AET“please input”的提示还在,而BET的提示在输入的时候已经消失了。



你更喜欢那种想必心中已有决定了吧。对你有帮助请点个赞。谢谢...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息