19.Android 清除按钮EditText - AIEditText

19.Android 清除按钮EditText - AIEditText


实现思路

1.继承AppCompatEditText类。
2.读取图片,每次都通过setCompoundDrawables将图片设置到EditText的右边。
3.实现OnFocusChangeListener接口,每次获得焦点的时候,进行一次文本的判断,如果有文本,显示图片;没有文本,隐藏图片。
4.实现View.OnTouchListener接口,每次onTouch的时候,判断是否点击到了图片,进行文本的清空。
5.实现TextWatcher接口,通过判断文本的长度,来决定图片是否显示。


继承AppCompatEditText类

    public AIEditText(Context context) {
        super(context);
        this.init(context);
    }

    public AIEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.init(context);
    }

    public AIEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.init(context);
    }

setCompoundDrawables设置图片

从TextView继承下来的方法setCompoundDrawables。

EditText也是TextView的子类,AppCompatEditText又是EditText的子类。

setCompoundDrawables(@Nullable Drawable left, @Nullable Drawable top,
@Nullable Drawable right, @Nullable Drawable bottom)

    /**
     * @param context
     */
    private void init(Context context) {
        Drawable drawable = ContextCompat.getDrawable(context, R.drawable.abc_ic_clear_mtrl_alpha);
        Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
        DrawableCompat.setTint(wrappedDrawable, super.getCurrentHintTextColor());
        this.mClearDrawable = wrappedDrawable;
        this.mClearDrawable.setBounds(0, 0, this.mClearDrawable.getIntrinsicHeight(), this.mClearDrawable.getIntrinsicHeight());
        this.setClearDrawableVisible(false);
        super.setOnTouchListener(this);
        super.setOnFocusChangeListener(this);
        this.addTextChangedListener(this);
    }

    private void setClearDrawableVisible(boolean visible) {
        this.mClearDrawable.setVisible(visible, false);
        final Drawable[] compoundDrawables = this.getCompoundDrawables();
        this.setCompoundDrawables(compoundDrawables[0], compoundDrawables[1], visible ? this.mClearDrawable : null, compoundDrawables[3]);
    }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值