/*** Created by xp.chen on 2016/11/25.*/

public class DJEditText extendsAppCompatEditText {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;privateDrawable mClearDrawable;publicDJEditText(Context context) {super(context);

init();

}publicDJEditText(Context context, AttributeSet attrs) {super(context, attrs);

init();

}public DJEditText(Context context, AttributeSet attrs, intdefStyleAttr) {super(context, attrs, defStyleAttr);

init();

}private voidinit() {

mClearDrawable=getResources().getDrawable(R.drawable.app_clear_btn_bg_selector);

}

@Overrideprotected void onTextChanged(CharSequence text, int start, int lengthBefore, intlengthAfter) {super.onTextChanged(text, start, lengthBefore, lengthAfter);

setClearIconVisible(hasFocus()&& length() > 0);

}

@Overrideprotected void onFocusChanged(boolean focused, intdirection, Rect previouslyFocusedRect) {super.onFocusChanged(focused, direction, previouslyFocusedRect);

setClearIconVisible(focused&& length() > 0);

}

@Overridepublic booleanonTouchEvent(MotionEvent event) {switch(event.getAction()) {caseMotionEvent.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(booleanvisible) {

setCompoundDrawablesWithIntrinsicBounds(getCompoundDrawables()[DRAWABLE_LEFT], getCompoundDrawables()[DRAWABLE_TOP]

,visible? mClearDrawable : null, getCompoundDrawables()[DRAWABLE_BOTTOM]);

}

}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐