Android-自定义带有删除图标的EditText

自定义EditText类

注意事项:
1、由于版本变化,自定义EditText类不能直接继承EditText类,而是AppCompatEditText类
2、获取Drawable
getResources().getDrawable(R.drawable.del);方法不再推荐使用
官方推荐方法ContextCompat.getDrawable(getContext(),R.drawable.del);

package com.android02;


import android.content.Context;

import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;

import android.view.MotionEvent;
import android.view.View;



/**
 * 输入文本框 右边有自带的删除按钮 当有输入时,显示删除按钮,当无输入时,隐藏删除按钮。
 */
 public class ClearEditText extends AppCompatEditText implements View.OnFocusChangeListener, TextWatcher {
    
    

     //删除按钮的引用
    private Drawable clearDrawable;

    // 控件是否有焦点
    private boolean hasFocus;

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

    public ClearEditText(Context context, AttributeSet attrs) {
    
    
        // 这里构造方法也很重要,不加这个很多属性不能再XML里面定义
        this(context, attrs, android.R.attr.editTextStyle);
    }

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

    private void init() {
    
    
        // 获取EditText的DrawableRight,假如没有设置我们就使用默认的图片
        clearDrawable = getCompoundDrawables()[2];
        if (clearDrawable == null) {
    
    
            // throw new
            // NullPointerException("You can add drawableRight attribute in XML");
            clearDrawable = ContextCompat.getDrawable(getContext(),R.drawable.del);
        }

        // 设置图标的大小
        clearDrawable.setBounds(0, 0, 60, 60);
        // 默认设置隐藏图标
        setClearIconVisible(false);
        // 设置焦点改变的监听
        setOnFocusChangeListener(this);
        // 设置输入框里面内容发生改变的监听
        addTextChangedListener(this);
    }

    /**
     * 因为我们不能直接给EditText设置点击事件,
     * 因此我们用记住我们按下的位置来模拟点击事件
     * 当我们按下的位置
     * 在 EditText的宽度 -图标到控件右边的间距 - 图标的宽度 和 EditText的宽度 - 图标到控件右边的间距之间我们就算点击了图标,
     * 竖直方向就没有考虑
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
    
    
        if (event.getAction() == MotionEvent.ACTION_UP) {
    
    
            if (getCompoundDrawables()[2] != null) {
    
    

                boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight()) && (event.getX() < ((getWidth() - getPaddingRight())));

                if (touchable) {
    
    
                    this.setText("");
                }
            }
        }
        return super.onTouchEvent(event);
    }

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

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

    /**
     * 当输入框里面内容发生变化的时候回调的方法
     */
    @Override
    public void onTextChanged(CharSequence s, int start, int count, int after) {
    
    
        if (hasFocus) {
    
    
            setClearIconVisible(s.length() > 0);
        }
    }

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

    }

    @Override
    public void afterTextChanged(Editable s) {
    
    

    }

}

布局

java目录下的包名+类名(我们自定义的EditText)

<com.android02.ClearEditText
                        android:id="@+id/username"
                        android:singleLine="true"
                        android:background="@null"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:inputType="text"
                        android:hint="用户名"
                        android:ems="10"
                         />

测试

在这里插入图片描述
搞定~

在这里插入图片描述
本文参考于https://blog.csdn.net/lengguoxing/article/details/42145467

猜你喜欢

转载自blog.csdn.net/m0_46267375/article/details/109035609