带有删除按钮的EditText

描述

虽然带有删除按钮的EditText不是太难写,但是为了记录自己学习过程,方便以后在项目中使用,写了此博客

效果图

这里写图片描述

实现步骤

1.写一个类集成EditText,起名为ClearEditText,重写构造方法,每一个构造方法内init()初始化数据;

 public ClearEditText(Context context) {
    this(context, null);
    init();
}

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

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

2. 先贴出来init()方法内的源码, 代码里面都有注释

    mClearDrawable = getCompoundDrawables()[2];
    //此方法是获取到DrawableRight的图片
    if (mClearDrawable == null) {
        mClearDrawable = getResources().getDrawable(R.drawable.delete);
    //如果DrawableRight没有图片, 我们添加自己的delete图片
    }
    mClearDrawable.setBounds(0, 0, (int)(mClearDrawable.getIntrinsicWidth()*0.4),(int)(mClearDrawable.getIntrinsicHeight()*0.4));
    //设置图片的上下左右的位置


    setClearIconVisible(false);
    //默认设置隐藏图标

    setOnFocusChangeListener(this);
    //设置焦点改变的监听

    addTextChangedListener(this);
    //设置输入框里面内容发生改变的监听

3.设置隐藏图标的方法

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

4.设置焦点改变的监听的方法

/**
 * 当ClearEditText焦点发生变化的时候,判断里面字符串长度设置清除图标的显示与隐藏
 */
@Override
public void onFocusChange(View v, boolean hasFocus) {
    this.hasFoucs = hasFocus;
    if (hasFocus) {
        setClearIconVisible(getText().length() > 0);
    } else {
        setClearIconVisible(false);
    }
}

5.监听输入框的改变

/**
 * 当输入框里面内容发生变化的时候回调的方法
 */
@Override
public void onTextChanged(CharSequence s, int start, int count,
                          int after) {
    //看此方法的名字就知道,当EditText里面的内容发生改变的时候会走此方法
    if(hasFoucs){
        setClearIconVisible(s.length() > 0);
    //当text长度大于0的时候显示清除按钮, 反之删除
    }

}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
                              int after) {

}

@Override
public void afterTextChanged(Editable s) {

}

源码位置 ClearEditText

猜你喜欢

转载自blog.csdn.net/qq_33408235/article/details/75393778
今日推荐