我解决了它……创建了以下代码
public class CustomEditText extends EditText {
private Drawable dRight;
private Rect rBounds;
CustomEditText(Context context,AttributeSet attributeSet){
super(context,attributeSet);
}
@Override
public void setCompoundDrawables(Drawable left,Drawable top,Drawable right,Drawable bottom) {
/*if (left != null) {
dLeft = left;
}*/
if (right != null) {
dRight = right;
}
super.setCompoundDrawables(left,top,right,bottom);
}
@Override
public void addTextChangedListener(TextWatcher watcher) {
super.addTextChangedListener(watcher);
}
@Override
protected void onTextChanged(CharSequence text,int start,int lengthBefore,int lengthAfter) {
super.onTextChanged(text,start,lengthBefore,lengthAfter);
if(this.getText().toString().length()>0)
this.setCompoundDrawablesWithIntrinsicBounds(null,dRight,null);
else
this.setCompoundDrawablesWithIntrinsicBounds(null,null);
}
@Override
protected void finalize() throws Throwable {
dRight = null;
rBounds = null;
super.finalize();
}
}
并添加到xml中:
android:id="@+id/uIDEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableRight="@drawable/round_clear"
android:textColor="#ffffff" />
在Activity中(edittext ontouch侦听器):
uIDEditText.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v,MotionEvent event) {
if (event.getAction() != MotionEvent.ACTION_UP)
return false;
if (event.getX() > uIDEditText.getWidth() - clear.getIntrinsicWidth())
{
uIDEditText.setText("");
event.setAction(MotionEvent.ACTION_CANCEL);
}
return false;
}
});