【android-android 带删除功能的EditText】将相本无种,男儿当自强。这篇文章主要讲述android-android 带删除功能的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]); } }
最终效果:
文章图片
推荐阅读
- Andromeda OS 来了,Android 再见()
- Android7.0 Vold 进程工作机制分析之整体流程
- Android五大布局之一绝对布局(AbsoluteLayout)
- React Native嵌入Android原生应用中
- 腾讯Android面经
- Android五大布局之一表格布局(TableLayout)
- Android:隐藏 EditText 在 Activity 中键盘自动弹出
- Android笔记——判断程序是否第一次启动
- Android Support 包知识