带删除按钮的EditText

2023-05-22,,

在使用输入框的时候,常常需要在输入框后带有一键清除输入内容的按钮。采用自定义View的方式是复用性较高的方法。另一方面也可以采用控件“控件+监听”的较为简单的方法来实现。

布局文件:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="账号:"
        android:textColor="#000000"
        android:gravity="center"
        android:textSize="16sp"/>
    <EditText
        android:id="@+id/etUser"
        tools:text="test3"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:background="@null"
        android:maxLength="16"
        android:layout_weight="1"/>
    <TextView
        android:id="@+id/closeUser"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:gravity="center"
        android:background="@drawable/icon_delete"
        android:textColor="@color/gray"/>
</LinearLayout>

主要代码:

        tvCloseUser = (TextView) findViewById(R.id.closeUser);//清除按钮,使用TextView
        tvCloseUser.setVisibility(View.INVISIBLE);
        
        mEtUserName = (EditText) findViewById(R.id.etUser);//文本框
        
        //监听文本变化
        mEtUserName.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0){
                    tvCloseUser.setVisibility(View.VISIBLE);
                }else{
                    tvCloseUser.setVisibility(View.GONE);
                }
            }
        });
        //点击清除文本
        tvCloseUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEtUserName.setText("");
            }
        });
        //监听焦点变化,没有焦点则清除按钮不可见
        mEtUserName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus && mEtUserName.getText().length() > 0){
                    tvCloseUser.setVisibility(View.VISIBLE);
                }else {
                    tvCloseUser.setVisibility(View.GONE);
                }
            }
        });

《带删除按钮的EditText.doc》

下载本文的Word格式文档,以方便收藏与打印。