ClearEditText 点击删除EditText 的内容

2020-03-11  本文已影响0人  勤劳的蚂蚁
image.png
public class ClearEditText extends android.support.v7.widget.AppCompatEditText implements
        View.OnFocusChangeListener, TextWatcher {


    /**
     * 删除按钮的引用
     */
    private Drawable mClearDrawable;

    public ClearEditText(Context context) {
        this(context, null);

    }

    public ClearEditText(Context context, AttributeSet attrs) {
        //这里构造方法也很重要,不加这个很多属性不能再XML里面定义
        this(context, attrs, android.R.attr.editTextStyle);
        initLength(  attrs,context);
    }

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


    private void init() {
        //获取EditText的DrawableRight,假如没有设置我们就使用默认的图片
        mClearDrawable = getCompoundDrawables()[0];
        if (mClearDrawable == null) {
            mClearDrawable = getResources()
                    .getDrawable(R.mipmap.bianji);
        }
        mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight());
        setClearIconVisible(true);
        setOnFocusChangeListener(this);
        addTextChangedListener(this);
    }


    private void initLength(AttributeSet a, Context context) {
        //命名空间(别告诉我不熟悉)
        String namespace = "http://schemas.android.com/apk/res/android";
        //获取属性中设置的最大长度
        int maxLength = a.getAttributeIntValue(namespace, "maxLength", -1);
        //如果设置了最大长度,给出相应的处理
        if (maxLength > -1) {
            setFilters(new InputFilter[]{new MyLengthFilter(maxLength, context)});
        }
    }


    /**
     * 因为我们不能直接给EditText设置点击事件,所以我们用记住我们按下的位置来模拟点击事件
     * 当我们按下的位置 在  EditText的宽度 - 图标到控件右边的间距 - 图标的宽度  和
     * EditText的宽度 - 图标到控件右边的间距之间我们就算点击了图标,竖直方向没有考虑
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
//        if (getCompoundDrawables()[0] != null) {
//            if (event.getAction() == MotionEvent.ACTION_UP) {
//                boolean touchable = event.getX() > (getWidth()
//                        - getPaddingRight() - mClearDrawable.getIntrinsicWidth())
//                        && (event.getX() < ((getWidth() - getPaddingRight())));
//                if (touchable) {
//                    this.setText("");
//                }
//            }
//        }

        return super.onTouchEvent(event);
    }

    /**
     * 当ClearEditText焦点发生变化的时候,判断里面字符串长度设置清除图标的显示与隐藏
     */
    @Override
    public void onFocusChange(View v, boolean hasFocus) {

        setClearIconVisible(!(getText().length() > 0));

    }


    /**
     * 设置清除图标的显示与隐藏,调用setCompoundDrawables为EditText绘制上去
     *
     * @param visible
     */
    protected void setClearIconVisible(boolean visible) {
        Drawable left = visible ? mClearDrawable : null;
        setCompoundDrawables(left,
                getCompoundDrawables()[1], getCompoundDrawables()[2], getCompoundDrawables()[3]);
    }


    /**
     * 当输入框里面内容发生变化的时候回调的方法
     */
    @Override
    public void onTextChanged(CharSequence s, int start, int count,
                              int after) {
        setClearIconVisible(!(s.length() > 0));
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {

    }

    @Override
    public void afterTextChanged(Editable s) {

    }


    /**
     * 设置晃动动画
     */
    public void setShakeAnimation() {
        this.setAnimation(shakeAnimation(5));
    }


    /**
     * 晃动动画
     *
     * @param counts 1秒钟晃动多少下
     * @return
     */
    public static Animation shakeAnimation(int counts) {
        Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0);
        translateAnimation.setInterpolator(new CycleInterpolator(counts));
        translateAnimation.setDuration(1000);
        return translateAnimation;
    }



   private class MyLengthFilter implements InputFilter {

        private final int mMax;
        private Context context;

        public MyLengthFilter(int max, Context context) {
            mMax = max;
            this.context = context;
        }

        /*   source 新输入的字符串
           start 新输入的字符串起始下标,一般为0
           end 新输入的字符串终点下标,一般为source长度-1
           dest 输入之前文本框内容
           dstart 原内容起始坐标,一般为0
           dend 原内容终点坐标,一般为dest长度-1*/
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                                   int dstart, int dend) {
            int keep = mMax - (dest.length() - (dend - dstart));
            if (keep <= 0) {
                //这里,用来给用户提示
                Toast.makeText(context, "字数不能超过" + mMax+"字", Toast.LENGTH_SHORT).show();
                return "";
            } else if (keep >= end - start) {
                return null; // keep original
            } else {
                keep += start;
                if (Character.isHighSurrogate(source.charAt(keep - 1))) {
                    --keep;
                    if (keep == start) {
                        return "";
                    }
                }
                return source.subSequence(start, keep);
            }
        }

        /**
         * @return the maximum length enforced by this input filter
         */
        public int getMax() {
            return mMax;
        }
    }


}



上一篇下一篇

猜你喜欢

热点阅读