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

android EditText里面的文字个数变化,提示自动取消

2015-08-10 16:58 525 查看
         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 o
4000
nTextChanged(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));

    }

如图,当有文字变化时下面的提示自动消失。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: