zoukankan      html  css  js  c++  java
  • android控件库(1)-带删除功能的EditText

    DJEditText.java

    /**
     * Created by xp.chen on 2016/11/25.
     */
    
    public class DJEditText 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 DJEditText(Context context) {
            super(context);
            init();
        }
    
        public DJEditText(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }
    
        public DJEditText(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            init();
        }
    
    
    
        private void init() {
            mClearDrawable = getResources().getDrawable(R.drawable.app_clear_btn_bg_selector);
        }
    
    
        @Override
        protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
            super.onTextChanged(text, start, lengthBefore, lengthAfter);
            setClearIconVisible(hasFocus() && 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;
                default:
                    break;
            }
            return super.onTouchEvent(event);
        }
    
    
        public void setClearIconVisible(boolean visible) {
            setCompoundDrawablesWithIntrinsicBounds(getCompoundDrawables()[DRAWABLE_LEFT], getCompoundDrawables()[DRAWABLE_TOP]
                    ,visible ? mClearDrawable : null, getCompoundDrawables()[DRAWABLE_BOTTOM]);
        }
    }

    最终效果:

  • 相关阅读:
    2019 Multi-University Training Contest 4
    AC自动机
    trie
    Contest1802
    蓝桥杯-某电视台举办了低碳生活大奖赛
    蓝桥杯-有一群海盗(不多于20人),在船上比拼酒量
    蓝桥杯-福尔摩斯到某古堡探险
    蓝桥杯-标题:字符串比较
    蓝桥杯-题目:猜算式
    蓝桥杯-标题:算年龄
  • 原文地址:https://www.cnblogs.com/yongdaimi/p/6101371.html
Copyright © 2011-2022 走看看