EditText里面的文字变化的时候,经常会出现一下提示字符,如输入错误密码,会提示密码错误,当我们点击EditText,修改密码,里面的文字个数有变动的时候,希望下面的这行字消失。用TextWatcher可以解决。TextWatcher为编辑框监听器。
在layout里面创建activity_main.xml文件。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#f4f4f4">
<EditText
android:id="@+id/edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:inputType="number"
android:maxLength="8"
android:text="12345"
android:textColor="#000000"/>
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:layout_marginRight="5dp"
android:text="你输入的密码有误"
android:textColor="#ff5077" />
</LinearLayout>
创建TextViewWatcher继承自TextWatcher。beforeTextChanged可以给出变化之前的内容,onTextChanged和afterTextChanged给出追加上新的字符之后的文本;
public class TextViewWatcher implements TextWatcher {
private TextView view;
public TextViewWatcher(TextView v) {
view = v;
}
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
view.setVisibility(View.INVISIBLE);
}
}
在MainActivity里面的onCreate直接调用
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit=(EditText)findViewById(R.id.edit);
text=(TextView)findViewById(R.id.text);
edit.addTextChangedListener(new TextViewWatcher(text));
}
如图,当有文字变化时下面的提示自动消失。