很简单也很常用的一个控件
不多说 直接开始吧!
1.继承EditText类
2.监听输入框的文字变化是否显示x
3.为显示的x做个点击事件即可
代码如下:
clearEditText类
public class clearEditText extends EditText {
private Drawable dRight;
private Rect rBounds;
public clearEditText(Context context) {
super(context);
initEditText();
}
public clearEditText(Context context, AttributeSet attrs) {
super(context, attrs);
initEditText();
}
public clearEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initEditText();
}
// 初始化edittext 控件
private void initEditText() {
setEditTextDrawable();
addTextChangedListener(new TextWatcher() {// 对文本内容改变进行监听
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
clearEditText.this.setEditTextDrawable();
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
// 控制图片的显示
public void setEditTextDrawable() {
if (getText().toString().length() == 0) {
setCompoundDrawables(null, null, null, null);
} else {
setCompoundDrawables(null, null, this.dRight, null);
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
this.dRight = null;
this.rBounds = null;
}
//添加触摸事件 点击之后 出现 清空editText的效果
@Override
public boolean onTouchEvent(MotionEvent event) {
if (this.dRight != null && event.getAction() == 1) {
this.rBounds = this.dRight.getBounds();
//
if (getSrceenX(event) > getRight() - 3 * this.rBounds.width()) {
setText("");
event.setAction(MotionEvent.ACTION_CANCEL);
}
}
return super.onTouchEvent(event);
}
// 距离屏幕的距离
private int getSrceenX(MotionEvent event){
return (int) event.getRawX();
}
//显示右侧X图片的
@Override
public void setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom) {
if (right != null) {
this.dRight = right;
}
super.setCompoundDrawables(left, top, right, bottom);
}
}
使用就直接在布局文件上面的添加即可
<com.toollibrary.ClearEditText.clearEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableRight="@drawable/sc"
android:id="@+id/et_selete"
android:layout_weight="1" />
其中添加了一个右侧的图片