Android 自定义带删除按钮的EditText

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35619188/article/details/84826344

首先创建一个类 设置成EditTextWithDel,继承EditText。
实现代码如下。

@SuppressLint("AppCompatCustomView")
public class EditTextWithDel extends EditText {

    private Drawable imgDrawable;
    private Context mContext;
    //构造函数
    public EditTextWithDel(Context context) {
        super(context);
        mContext= context;
        init();
    }

    public EditTextWithDel(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext=context;
        init();
    }

    public EditTextWithDel(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        init();
    }
    //监听输入框的输入值
    private void init(){
        imgDrawable =mContext.getResources().getDrawable(R.mipmap.ic_launcher);
        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();
            }
        });
        setDrawable();
    }
    //设置删除图片
    private void setDrawable(){
        if(length()<1)
            setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);
        else
//这里设置删除图片            setCompoundDrawablesWithIntrinsicBounds(null,null,imgDrawable,null);
    }


    //处理删除事件
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //如果图片不为空  手指离开屏幕
        //手指的初次触摸(ACTION_DOWN操作),滑动(ACTION_MOVE操作)和抬起(ACTION_UP)
        if (imgDrawable!=null&&event.getAction()==MotionEvent.ACTION_UP)
        {
            //获取点击的屏幕坐标
            int eventX =(int)event.getRawX();
            int eventY = (int) event.getRawY();
            //根据指定坐标创建一个长方形
            Rect rect = new Rect();
            //getGlobalVisibleRect方法的作用是获取视图在屏幕坐标系中的偏移量
            //getLocalVisibleRect(Rect r)方法可以把视图的长和宽映射到一个Rect对象上。
            getGlobalVisibleRect(rect);
            if (rect.contains(eventX,eventY)){
                setText("");
            }
        }
        return super.onTouchEvent(event);
    }

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

参考链接

猜你喜欢

转载自blog.csdn.net/qq_35619188/article/details/84826344