Android:带一键清除功能的EditText

作为一个前端应用开发者,下面这样的场景可以说是屡见不鲜了?

《Android:带一键清除功能的EditText》 20181218135459.png

当然了,本文所要讲的重点不是如何做一个登录页面,而是输入框后面的那个清除按钮。你可能会说了,这有什么好讲的,在EditText后面加一个按钮就行了。没错,这样也可以实现想要的效果,但是如果一个页面有10个甚至更多的EditText,那就意味着你的布局会变得很臃肿,并且需要为每个EditText设置监听来控制其删除按钮的显隐。可见这并不是一个完美的解决方案。

思路分析

看了上面的场景分析,我们下面就来整理一下思路,自定义一个带清除功能的EditText来满足这样的需求。

  1. 布局组合封装
    即组合EditText和删除按钮,封装成一个整体来使用,这种方式也是比较常见的自定组件方式,其本质就是利用基础组件拼装,然后封装成模块化的组件避免重复码代码。日常的开发过程中这种模式基本上能够解决大多数的功能场景,也不失为一个良策。
  2. 对EditText本身动刀
    对于android开发者来说CompoundDrawable并不陌生吧,这里第二个思路就是利用这个属性来实现一键清除功能。

    《Android:带一键清除功能的EditText》 20181218165750.png

以上图为例,我们这个条思路重点要处理的就是C到E的这块区域,通过监听touch时间来模拟点击事件,那么我们就需要获取一下几个参数:

  • getWidth()获取整个控件的宽度
  • getTotalPaddingRight()图标左边缘至控件右边缘的距离,也就是D->E的距离
  • getCompoundDrawablePadding()表示从文本右边到图标左边缘的距离,也就是C->D的距离

因此就可以通过getWidth() – getTotalPaddingRight() – getCompoundDrawablePadding()来获取到C的位置,这样当ACTION_UP事件触发的时候只要触摸点在C到E之间我们就认为是点击了清除按钮。
接下来最后一件事儿就是通过TextWatcher和View.OnFocusChangeListener来设置和清除CompoundDrawable了。

撸代码

其实思路理通了,代码写起来就非常简单了,下面我就给出完整的代码,并在里面做出详细的注释。

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * 继承AppCompatEditText并实现TextWatcher和OnFocusChangeListener 
 */
public class ClearEditText extends AppCompatEditText
        implements TextWatcher, View.OnFocusChangeListener {

    private Drawable mClearDrawable;//清除按钮图片
    private boolean hasFocus;

    private TextWatcher mTextWatcher;
    private OnFocusChangeListener mOnFocusChangeListener;

    /**
     *构造函数常规操作,这里不做过多的说明
     */
    public ClearEditText(Context context) {
        this(context, null);
    }

    public ClearEditText(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.editTextStyle);
    }

    public ClearEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        hasFocus = hasFocus();
        //获取清除图标,这个图标是通过布局文件里面的drawableEnd或者drawableRight来设置的
        //getCompoundDrawables:Returns drawables for the left, top, right, and bottom borders.
        //getCompoundDrawablesRelative:Returns drawables for the start, top, end, and bottom borders.
        mClearDrawable = getCompoundDrawables()[2];
        if(mClearDrawable == null) {
            mClearDrawable = getCompoundDrawablesRelative()[2];
        }
        if(mClearDrawable != null) {
            //设置图标的位置以及大小,getIntrinsicWidth()获取显示出来的大小而不是原图片的带小
            mClearDrawable.setBounds(0, 0,
                    mClearDrawable.getIntrinsicWidth(),
                    mClearDrawable.getIntrinsicHeight());
        }
        //默认设置隐藏图标
        setClearIconVisible(false);
        //设置焦点改变的监听
        setOnFocusChangeListener(this);
        //设置输入框里面内容发生改变的监听
        addTextChangedListener(this);
    }

    /**
     * 用记住我们按下的位置来模拟点击事件
     * 当我们按下的位置在 EditText的宽度 - 文本右边到图标左边缘的距离 - 图标左边缘至控件右边缘的距离
     * 到 EditText的右边缘 之间就算点击了图标,竖直方向就以 EditText高度为边界
    */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP && mClearDrawable != null) {
            //getTotalPaddingRight()图标左边缘至控件右边缘的距离
            //getCompoundDrawablePadding()表示从文本右边到图标左边缘的距离
            int left = getWidth() - getTotalPaddingRight() - getCompoundDrawablePadding();
            boolean touchable = event.getX() > left && event.getX() < getWidth();
            if (touchable) {
                this.setText("");
            }
        }
        return super.onTouchEvent(event);
    }

    /**
     * 当ClearEditText焦点发生变化的时候:
     * 有焦点并且输入的文本内容不为空时则显示清除按钮
     */
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        this.hasFocus = hasFocus;
        setClearIconVisible(hasFocus && !TextUtils.isEmpty(getText()));
        if(mOnFocusChangeListener != null){
            mOnFocusChangeListener.onFocusChange(v, hasFocus);
        }
    }


    /**
     * 当输入框里面内容发生变化的时候:
     * 有焦点并且输入的文本内容不为空时则显示清除按钮
     */
    @Override
    public void onTextChanged(CharSequence s, int start, int count, int after) {
        setClearIconVisible(hasFocus && s.length() > 0);
        if(mTextWatcher != null){
            mTextWatcher.onTextChanged(s, start, count, after);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        if(mTextWatcher != null){
            mTextWatcher.beforeTextChanged(s, start, count, after);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
        if(mTextWatcher != null){
            mTextWatcher.afterTextChanged(s);
        }
    }

    /**
     * 设置清除图标的显示与隐藏,调用setCompoundDrawables为EditText绘制上去
     * @param visible
     */
    protected void setClearIconVisible(boolean visible) {
        if(mClearDrawable == null) return;
        Drawable right = visible ? mClearDrawable : null;
        setCompoundDrawables(getCompoundDrawables()[0],
                getCompoundDrawables()[1], right, getCompoundDrawables()[3]);
    }

    /**
     * 1、是自己本身的话则调用父类的实现,
     * 2、是外部设置的就自己处理回调回去
     */
    @Override
    public void setOnFocusChangeListener(OnFocusChangeListener l) {
        if(l instanceof ClearEditText){
            super.setOnFocusChangeListener(l);
        } else {
            mOnFocusChangeListener = l;
        }
    }

    @Override
    public void addTextChangedListener(TextWatcher watcher) {
        if(watcher instanceof ClearEditText){
            super.addTextChangedListener(watcher);
        } else {
            mTextWatcher = watcher;
        }
    }
}

总结

到这里就算完成了这次的自定义,实现了带一键清除功能的EditText,功能比较简单,我就不放GitHub。总结一下几点:

  • 使用CompoundDrawable来代替清除按钮
  • 通过getWidth() – getTotalPaddingRight() – getCompoundDrawablePadding()来计算响应范围
  • 实现TextWatcher和View.OnFocusChangeListener来控制CompoundDrawable的显示
  • 最后通过setCompoundDrawables来绘制清除按钮

这样的代码我想百度一大堆,如果你只是要代码完全copy就可以了,但我认为作为一个开发者来说,理清思路才是最重要的,这也是为什么我前面唠唠叨叨的讲很多的原因。
如果有说错的或者理解不到位的地方都可以指出来,我们一起学习改正,谢谢!

    原文作者:SupKing_a520
    原文地址: https://www.jianshu.com/p/6b2b0f6873db
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞