Android自定义带删除按钮的EditText

我不是女神ヾ 2022-03-15 02:12 454阅读 0赞

前言

为了提升用户体验,很多时候我们都需要在输入框后面添加“一键清空”按钮,比如输入账号密码时。实现起来也很简单,可以直接在EditText外面包裹一层FrameLayout,然后添加一个删除按钮。但是这样子逻辑稍微复杂,如果很多地方用的话还是很麻烦的。所以今天我们来实现一个带删除按钮的EditText,简化我们的开发过程。

截图

关键代码

  1. public class ClearableEditText extends AppCompatEditText {
  2. private static final int DRAWABLE_LEFT = 0;
  3. private static final int DRAWABLE_TOP = 1;
  4. private static final int DRAWABLE_RIGHT = 2;
  5. private static final int DRAWABLE_BOTTOM = 3;
  6. private Drawable mClearDrawable;
  7. public ClearableEditText(Context context) {
  8. super(context);
  9. init();
  10. }
  11. public ClearableEditText(Context context, AttributeSet attrs) {
  12. super(context, attrs);
  13. init();
  14. }
  15. public ClearableEditText(Context context, AttributeSet attrs, int defStyleAttr) {
  16. super(context, attrs, defStyleAttr);
  17. init();
  18. }
  19. private void init() {
  20. mClearDrawable = getResources().getDrawable(R.drawable.ic_edit_text_clear);
  21. }
  22. @Override
  23. protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
  24. super.onTextChanged(text, start, lengthBefore, lengthAfter);
  25. setClearIconVisible(hasFocus() && text.length() > 0);
  26. }
  27. @Override
  28. protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
  29. super.onFocusChanged(focused, direction, previouslyFocusedRect);
  30. setClearIconVisible(focused && length() > 0);
  31. }
  32. @Override
  33. public boolean onTouchEvent(MotionEvent event) {
  34. switch (event.getAction()) {
  35. case MotionEvent.ACTION_UP:
  36. Drawable drawable = getCompoundDrawables()[DRAWABLE_RIGHT];
  37. if (drawable != null && event.getX() <= (getWidth() - getPaddingRight())
  38. && event.getX() >= (getWidth() - getPaddingRight() - drawable.getBounds().width())) {
  39. setText("");
  40. }
  41. break;
  42. }
  43. return super.onTouchEvent(event);
  44. }
  45. private void setClearIconVisible(boolean visible) {
  46. setCompoundDrawablesWithIntrinsicBounds(getCompoundDrawables()[DRAWABLE_LEFT], getCompoundDrawables()[DRAWABLE_TOP],
  47. visible ? mClearDrawable : null, getCompoundDrawables()[DRAWABLE_BOTTOM]);
  48. }
  49. }
  50. 复制代码

使用

直接将layout中的EditText改为your package name.ClearableEditText即可。 如果没有依赖v7包需将其继承的AppCompatEditText改为普通的EditText。

源码下载

迁移自我的简书 2016.03.09

发表评论

表情:
评论列表 (有 0 条评论,454人围观)

还没有评论,来说两句吧...

相关阅读

    相关 定义EditText

    这几天想要做一种类似于淘宝App的登录界面,看着淘宝上的EditText真是好看,它换了底线,换了光标。应该是继承EditText后重写的onDrow方法。那么它具体是怎么实现