Android EditText 自定义带删除按钮

EditText里面带删除按钮在各种App里面已经很常见了,如下:

所需的图片资源:

这里写图片描述

下面直接贴上全部代码:

public class ClearEditText extends EditText implements OnFocusChangeListener, TextWatcher {

    private Drawable mClearDrawable;

    private boolean hasFoucs;

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

    public ClearEditText(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.editTextStyle);
    }

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

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

    /** * 因为我们不能直接给EditText设置点击事件,所以我们用记住我们按下的位置来模拟点击事件 当我们按下的位置 在 EditText的宽度 - * 图标到控件右边的间距 - 图标的宽度 和 EditText的宽度 - 图标到控件右边的间距之间我们就算点击了图标,竖直方向就没有考虑 */
    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        //监听手指的按下、滑动、抬起来达到图片的点击,按住效果
        switch (action) {
        case MotionEvent.ACTION_DOWN:
            if (getCompoundDrawables()[2] != null && getText().length() > 0) {
                boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight())
                        && (event.getX() < ((getWidth() - getPaddingRight())));
                if (touchable) {
                    setIconChange(R.drawable.nickname_delete2);
                }
            }
            break;
        case MotionEvent.ACTION_MOVE:

            if (getCompoundDrawables()[2] != null && getText().length() > 0) {
                boolean touchable = (event.getX() > (getWidth() - getTotalPaddingRight()) && (event
                        .getX() < ((getWidth() - getPaddingRight()))))
                        && (event.getY() > 0 && event.getY() < getHeight() + 100);

                if (touchable) {
                    setIconChange(R.drawable.nickname_delete2);
                } else {
                    setIconChange(R.drawable.nickname_delete);
                }
            }

            break;
        case MotionEvent.ACTION_UP:
            if (getCompoundDrawables()[2] != null && getText().length() > 0) {
                setIconChange(R.drawable.nickname_delete);
                boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight())
                        && (event.getX() < ((getWidth() - getPaddingRight())))
                        && (event.getY() > 0 && event.getY() < getHeight());

                if (touchable) {
                    this.setText("");
                }
            }
            break;
        }

        return super.onTouchEvent(event);
    }

    /** * 当ClearEditText焦点发生变化的时候,判断里面字符串长度设置清除图标的显示与隐藏 */
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        this.hasFoucs = hasFocus;
        if (hasFocus) {
            setClearIconVisible(getText().length() > 0);
        } else {
            setClearIconVisible(false);
        }
    }

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

    /** * 设置清除图标的点击效果变化 */
    private void setIconChange(int res) {
        mClearDrawable = getResources().getDrawable(res);

        mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(),
                mClearDrawable.getIntrinsicHeight());
        setCompoundDrawables(getCompoundDrawables()[0],
                getCompoundDrawables()[1], mClearDrawable,
                getCompoundDrawables()[3]);

    }

    /** * 当输入框里面内容发生变化的时候回调的方法TextWatcher */
    @Override
    public void onTextChanged(CharSequence s, int start, int count, int after) {
        if (hasFoucs) { 
        //当edittext里面有内容时显示删除图标
            setClearIconVisible(s.length() > 0);
        }
    }

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

    }

    @Override
    public void afterTextChanged(Editable s) {

    }

}

注释已经写的差不多了,这里就不多说了。使用方法(跟正常EditText一样使用):
在xml中:

<控件所在包路径.ClearEditText
                    android:id="@+id/clear_et"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="11"
                    android:hint="请输入您的手机号"
                    android:inputType="numberDecimal"
                    android:maxEms="11"
                    android:maxLength="11"
                    android:paddingBottom="12dp"
                    android:paddingLeft="10dp"
                    android:paddingRight="10dp"
                    android:paddingTop="12dp"
                    android:singleLine="true"
                    android:text=""
                    android:textColor="#000000"
                    android:textColorHint="#bbbbbb"
                    android:textSize="16sp" />

你可能感兴趣的:(android,EditText)