以下是一个示例代码,展示了如何在Android搜索视图中添加一个清除文本按钮的监听器:
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
public class ClearableEditText extends EditText {
    // 清除按钮的图标
    private Drawable clearButton;
    public ClearableEditText(Context context) {
        super(context);
        init();
    }
    public ClearableEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    public ClearableEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }
    private void init() {
        // 获取清除按钮的图标
        clearButton = getResources().getDrawable(android.R.drawable.ic_menu_close_clear_cancel);
        // 设置清除按钮的位置
        setCompoundDrawablesWithIntrinsicBounds(null, null, clearButton, null);
        // 添加文本改变的监听器
        addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 根据文本的长度显示或隐藏清除按钮
                setClearButtonVisible(s.length() > 0);
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        // 添加触摸事件监听器,点击清除按钮时清空文本
        setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (getCompoundDrawables()[2] != null) {
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        if (event.getX() > getWidth() - getPaddingRight() - clearButton.getIntrinsicWidth()) {
                            setText("");
                            return true;
                        }
                    }
                }
                return false;
            }
        });
    }
    // 设置清除按钮的可见性
    private void setClearButtonVisible(final boolean visible) {
        setCompoundDrawablesWithIntrinsicBounds(null, null, visible ? clearButton : null, null);
    }
}
使用这个ClearableEditText自定义控件替换你的搜索视图中的EditText,它会添加一个清除文本按钮的监听器,并在文本改变时显示或隐藏清除按钮。点击清除按钮会清空文本。