在开发中需要用到edittext,进行一些输入,但是一个一个删除又有点麻烦,所以就需要可以带删除的edittext,网络上有很多的方法自己找了一下都大同小异,这是自己项目中用到的方法():
R.drawable.delete_edit_login_black
是删除图片,可以自己修改添加。
public class DelEditText extends EditText { private Drawable errorDrable; public DelEditText (Context context) { super(context); Drawable dr = getResources().getDrawable(R.drawable.delete_edit_login_black); setErrorDrable(dr); } public DelEditText (Context context, AttributeSet attrs) { super(context, attrs); Drawable dr = getResources().getDrawable(R.drawable.delete_edit_login_black); setErrorDrable(dr); } public DelEditText (Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); Drawable dr = getResources().getDrawable(R.drawable.delete_edit_login_black); setErrorDrable(dr); } public void setErrorDrable(Drawable drable) { if (drable != null) { drable.setBounds(0, 0, drable.getIntrinsicWidth(), drable.getIntrinsicHeight()); } errorDrable = drable; } @Override protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { super.onTextChanged(text, start, lengthBefore, lengthAfter); if (TextUtils.isEmpty(text)) { Drawable[] drawables = getCompoundDrawables(); setCompoundDrawables(drawables[0], drawables[1], null, drawables[3]); } else { Drawable[] drawables = getCompoundDrawables(); setCompoundDrawables(drawables[0], drawables[1], errorDrable, drawables[3]); } } @Override protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { super.onFocusChanged(focused, direction, previouslyFocusedRect); if (focused){ setSelection(getText().length()); } } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP){ if(event.getX() > getWidth()-errorDrable.getIntrinsicWidth()-20){ setText(""); } } return super.onTouchEvent(event); } }