文本輸入框如果需要后邊帶個刪除按鈕的話泣刹,可以用下邊的自定義控件助析。
只要設(shè)置如下即可。
QQ截圖20171025142511.png
原理很簡單椅您,就是取drawableRight的圖片外冀,監(jiān)聽觸摸事件,看點擊的位置是不是drawableRight圖片的位置掀泳,是的話就執(zhí)行刪除操作雪隧,也就是把文本置空,setText=""而已.
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
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;
/**
*
* @author Sage
* 2017/4/19
*/
public class EditTextRightClear extends AppCompatEditText {
public EditTextRightClear(Context context) {
super(context);
initEditText();
}
public EditTextRightClear(Context context, AttributeSet attrs) {
super(context, attrs);
initEditText();
}
public EditTextRightClear(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initEditText();
}
private Drawable dBottom;
private Drawable dRight;
private Rect rBounds;
private void initEditText() {
setEditTextDrawable();
setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
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) {
setEditTextDrawable();
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
/**控制圖片的顯示*/
private void setEditTextDrawable() {
if (isFocused()) {
if (getText().toString().length() == 0) {
setCompoundDrawables(null, null, null, this.dBottom);
} else {
setCompoundDrawables(null, null, this.dRight, this.dBottom);
}
} else{
setCompoundDrawables(null, null, null, this.dBottom);
}
}
@Override
protected void finalize() throws Throwable {
super.finalize();
this.dRight = null;
this.dBottom = null;
this.rBounds = null;
}
// 添加觸摸事件
@Override
public boolean onTouchEvent(MotionEvent paramMotionEvent) {
if (paramMotionEvent.getAction() == MotionEvent.ACTION_UP && dRight != null) {
rBounds = dRight.getBounds();
float x = paramMotionEvent.getRawX();
int width = this.getRight();
if (x >= (width - rBounds.width() - getPaddingRight())) {
this.setText("");
paramMotionEvent.setAction(MotionEvent.ACTION_CANCEL);
}
}
return super.onTouchEvent(paramMotionEvent);
}
// 設(shè)置顯示的圖片資源
@Override
public void setCompoundDrawables(Drawable paramDrawable1, Drawable paramDrawable2,
Drawable paramDrawable3, Drawable paramDrawable4) {
if (paramDrawable3 != null) {
this.dRight = paramDrawable3;
}
if (paramDrawable4 != null) {
this.dBottom = paramDrawable4;
}
super.setCompoundDrawables(paramDrawable1, paramDrawable2, paramDrawable3, paramDrawable4);
}
}