android-android 帶刪除功能的EditText

來源:互聯網
上載者:User

標籤:get   nbsp   void   image   touch   bre   att   use   prot   

 

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]);    }}

 

最終效果:

 

android-android 帶刪除功能的EditText

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.