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]);
}