类:
packageview.design.jaesoon.editclearmodule;
importandroid.graphics.drawable.Drawable;
importandroid.text.Editable;
importandroid.text.TextWatcher;
importandroid.view.MotionEvent;
importandroid.view.View;
importandroid.widget.EditText;
/**
* Created by Jsesoon on 2016/5/10.
*/
public classEditClearListenerimplementsView.OnTouchListener,View.OnFocusChangeListener,TextWatcher {
privateEditTexteditText;
publicEditClearListener(EditText editText) {
this.editText= editText;
editText.setOnTouchListener(this);
editText.setOnFocusChangeListener(this);
editText.addTextChangedListener(this);
}
@Override
public voidonFocusChange(View v, booleanhasFocus) {
if(editText.getText().toString().length() >0) {
if(hasFocus) {
Drawable drawable =null;
if(android.os.Build.VERSION.SDK_INT>= android.os.Build.VERSION_CODES.LOLLIPOP) {
drawable = v.getContext().getResources().getDrawable(R.mipmap.ic_launcher,v.getContext().getTheme());
}else{
drawable = v.getContext().getResources().getDrawable(R.mipmap.ic_launcher);
}
// 这一步必须要做,否则不会显示.
drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
editText.setCompoundDrawables(null, null,drawable, null);
}else{
editText.setCompoundDrawables(null, null, null, null);
}
}
}
@Override
public booleanonTouch(View v,MotionEvent event) {
switch(event.getAction()) {
caseMotionEvent.ACTION_UP:
EditText editText = (EditText) v;
booleanisClean = (event.getX() > (editText.getWidth() - editText.getTotalPaddingRight())) &&
(event.getX() < (editText.getWidth() - editText.getPaddingRight()));
if(isClean) {
editText.setText("");
}
break;
}
return false;
}
@Override
public voidbeforeTextChanged(CharSequence s, intstart, intcount, intafter) {
}
@Override
public voidonTextChanged(CharSequence s, intstart, intbefore, intcount) {
if(editText.getText().toString().length() >0) {
Drawable drawable =null;
if(android.os.Build.VERSION.SDK_INT>= android.os.Build.VERSION_CODES.LOLLIPOP) {
drawable =editText.getContext().getResources().getDrawable(R.mipmap.ic_launcher,editText.getContext().getTheme());
}else{
drawable =editText.getContext().getResources().getDrawable(R.mipmap.ic_launcher);
}
// 这一步必须要做,否则不会显示.
drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
editText.setCompoundDrawables(null, null,drawable, null);
}else{
editText.setCompoundDrawables(null, null, null, null);
}
}
@Override
public voidafterTextChanged(Editable s) {
}
}
使用方法:
EditText et = new EditText;
new EditClearListener(et);