美文网首页Android DemoAndroid 自定义viewAndroid Other
Android自定义带删除按钮的EditText

Android自定义带删除按钮的EditText

作者: 王晨彦 | 来源:发表于2016-03-09 13:04 被阅读2707次

    前言

    为了提升用户体验,很多时候我们都需要在输入框后面添加“一键清空”按钮,比如输入账号密码时。实现起来也很简单,可以直接在EditText外面包裹一层FrameLayout,然后添加一个删除按钮。但是这样子逻辑稍微复杂,如果很多地方用的话还是很麻烦的。所以今天我们来实现一个带删除按钮的EditText,简化我们的开发过程。

    截图

    效果图

    关键代码

    public class ClearableEditText extends AppCompatEditText {
        private static final int DRAWABLE_LEFT = 0;
        private static final int DRAWABLE_TOP = 1;
        private static final int DRAWABLE_RIGHT = 2;
        private static final int DRAWABLE_BOTTOM = 3;
        private Drawable mClearDrawable;
    
        public ClearableEditText(Context context) {
            super(context);
            init();
        }
    
        public ClearableEditText(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }
    
        public ClearableEditText(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            init();
        }
    
        private void init() {
            mClearDrawable = getResources().getDrawable(R.drawable.ic_edit_text_clear);
        }
    
        @Override
        protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
            super.onTextChanged(text, start, lengthBefore, lengthAfter);
            setClearIconVisible(hasFocus() && text.length() > 0);
        }
    
        @Override
        protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
            super.onFocusChanged(focused, direction, previouslyFocusedRect);
            setClearIconVisible(focused && length() > 0);
        }
    
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_UP:
                    Drawable drawable = getCompoundDrawables()[DRAWABLE_RIGHT];
                    if (drawable != null && event.getX() <= (getWidth() - getPaddingRight())
                            && event.getX() >= (getWidth() - getPaddingRight() - drawable.getBounds().width())) {
                        setText("");
                    }
                    break;
            }
            return super.onTouchEvent(event);
        }
    
        private void setClearIconVisible(boolean visible) {
            setCompoundDrawablesWithIntrinsicBounds(getCompoundDrawables()[DRAWABLE_LEFT], getCompoundDrawables()[DRAWABLE_TOP],
                    visible ? mClearDrawable : null, getCompoundDrawables()[DRAWABLE_BOTTOM]);
        }
    }
    

    使用

    直接将layout中的EditText改为$your package name$.ClearableEditText即可。
    如果没有依赖v7包需将其继承的AppCompatEditText改为普通的EditText。

    源码下载

    相关文章

      网友评论

      本文标题:Android自定义带删除按钮的EditText

      本文链接:https://www.haomeiwen.com/subject/piozkttx.html