自定义EditText实现一键删除

本文介绍了一种自定义的EditText组件,该组件能够在获得焦点且含有文本时显示删除按钮,便于用户快速清除输入内容。通过继承EditText并实现OnFocusChangeListener接口,结合Drawable设置与触摸事件监听,实现了按钮的动态显示与响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义ETextWithDelete,当有焦点并且有文字内容时,出现一键删除键:

public class ETextWithDelete extends EditText implements View.OnFocusChangeListener {

    private Drawable drawable;
    private Context mContext;
    private EditText tmpEditText;
    private boolean focused = false;

    public ETextWithDelete(Context context) {
        super(context);
        init();
    }

    public ETextWithDelete(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public ETextWithDelete(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        mContext = context;
        TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.ETWithDelete);
        drawable = attributes.getDrawable(R.styleable.ETWithDelete_delSrc);
        attributes.recycle();
        init();
    }

    private void init() {
        if (drawable == null){
            drawable = ContextCompat.getDrawable(mContext, R.mipmap.edt_delete_all);
        }
        setOnFocusChangeListener(this);
        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) {
                setDrawable();
            }
        });
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        this.focused = hasFocus;
        if (focused && length() > 0) {
            setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
        } else {
            setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        }
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        this.focused = focused;
        if (focused && length() > 0) {
            setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
        } else {
            setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        }
    }

    private void setDrawable() {
        if (length() <= 0 || !focused) {
            setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        } else {
            drawable.setBounds(0, 0, Utils.Dp2Px(mContext, 15), Utils.Dp2Px(mContext, 15));
            setCompoundDrawables(null, null, drawable, null);
        }
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (drawable != null && event.getAction() == MotionEvent.ACTION_UP) {
            int x = (int) event.getX();
            //判断触摸点是否在水平范围内
            boolean isInnerWidth = (x > (getWidth() - getTotalPaddingRight())) && (x < (getWidth() - getPaddingRight()));
            //获取删除图标的边界,返回一个Rect对象
            Rect rect = drawable.getBounds();
            //获取删除图标的高度
            int height = rect.height();
            int y = (int) event.getY();
            //计算图标底部到控件底部的距离
            int distance = (getHeight() - height) / 2;
            //判断触摸点是否在竖直范围内(可能会有点误差)
            //触摸点的纵坐标在distance到(distance+图标自身的高度)之内,则视为点中删除图标
            boolean isInnerHeight = (y > distance) && (y < (distance + height));
            if (isInnerWidth && isInnerHeight) {
                setText("");
                if (tmpEditText != null)
                    tmpEditText.setText("");
            }
        }
        return super.onTouchEvent(event);
    }

    public void setTmpEditText(EditText tmpEditText) {
        this.tmpEditText = tmpEditText;
    }
}

Utils

public class Utils {

    /**
     * dp转px
     * @param dp
     * @return
     */
    public static int Dp2Px(Context context, float dp) {
        return (int) (dp * context.getResources().getDisplayMetrics().density+0.5f);
    }

    /**
     * px转dp
     * @param px
     * @return
     */
    public static int Px2Dp(Context context, float px) {
        return (int) (px / context.getResources().getDisplayMetrics().density + 0.5f);
    }

}
res/values/attrs下

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- 可清空编辑框属性 -->
    <declare-styleable name="ETWithDelete">
        <attr name="delSrc" format="reference" />
    </declare-styleable>
    <declare-styleable name="DottedLine">
        <attr name="dotColor" format="color" />
    </declare-styleable>
</resources>
使用,自定义删除图片

xmlns:app="http://schemas.android.com/apk/res-auto"

<包名.ETextWithDelete
	app:delSrc="@mipmap/edt_login_delete"
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	/>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值