前言
為了提升用戶(hù)體驗(yàn),很多時(shí)候我們都需要在輸入框后面添加“一鍵清空”按鈕坝锰,比如輸入賬號(hào)密碼時(shí)粹懒。實(shí)現(xiàn)起來(lái)也很簡(jiǎn)單,可以直接在EditText外面包裹一層FrameLayout什黑,然后添加一個(gè)刪除按鈕崎淳。但是這樣子邏輯稍微復(fù)雜,如果很多地方用的話(huà)還是很麻煩的愕把。所以今天我們來(lái)實(shí)現(xiàn)一個(gè)帶刪除按鈕的EditText,簡(jiǎn)化我們的開(kāi)發(fā)過(guò)程森爽。
截圖
關(guān)鍵代碼
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即可恨豁。
如果沒(méi)有依賴(lài)v7包需將其繼承的AppCompatEditText改為普通的EditText。