想要使用android自带的editText的drawable实现右边取消按钮的设置,但是设置之后,drawableRight并没有点击事件,因此本文在继承editText的基础上增加 setClearDrawMode属性,可以直接在layout的xml文件中配置
实现上述功能,第一步在values下新建 attrs.xml文件
<?xml version="1.0" encoding="utf-8"?> <resources> <!--带清除按钮的EditText--> <declare-styleable name="UpEditText"> <!-- 清除按钮显示模式 --> <attr name="clearDrawMode"> <!--不显示清空按钮--> <enum name="never" value="0" /> <!--不为空,且在编辑状态时(及获得焦点)显示清空按钮--> <enum name="whileEditing" value="1" /> </attr> </declare-styleable> </resources>
第二步新建UpEditText 继承EditText类
public class UpEditText extends AppCompatEditText { //setCompoundDrawable() 0 left, 1 top, 2 right, 3 bottom private static int LEFT = 0; private static int RIGHT= 2; private Context context; //EditText的显示模式 0 从不显示,1 当编辑的时候显示 private ClearDrawMode clearDrawMode; private int picId = R.drawable.cancel; public UpEditText(Context context) { super(context); init(context, null, 0); } public UpEditText(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs, 0); } public UpEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr); } private void init(Context context, AttributeSet attributeSet,int defStyleAttr){ this.context = context; TypedArray typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.UpEditText); int attr = typedArray.getInteger(R.styleable.UpEditText_clearDrawMode,picId); typedArray.recycle(); switch (attr){ case 1: clearDrawMode = ClearDrawMode.WHILEEDITING; break; default: clearDrawMode = ClearDrawMode.NEVER; break; } this.setCompoundDrawables(null,null,null,null); } public enum ClearDrawMode{ NEVER, WHILEEDITING } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.save(); buttonManager(); canvas.restore(); } public void buttonManager(){ switch (clearDrawMode){ case WHILEEDITING: if(hasFocus() && getText().length() > 0){ Drawable drawPicRight = getResources().getDrawable(R.drawable.cancel,null); drawPicRight.setBounds(1,1,60,60); this.setCompoundDrawables(null,null,drawPicRight,null); }else if(getText().length() == 0){ this.setCompoundDrawables(null,null,null,null); } break; default: this.setCompoundDrawables(null,null,null,null); break; } } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_UP: Drawable drawableRight = this.getCompoundDrawables()[RIGHT]; if (drawableRight != null && event.getRawX() >= (this.getRight() - (drawableRight.getBounds().width()) - getPaddingRight())){ this.setText(null); this.setCompoundDrawables(null,null,null,null); } break; } return super.onTouchEvent(event); } public void setClearDrawMode(ClearDrawMode clearDrawMode) { this.clearDrawMode = clearDrawMode; } public void setPicId(int picId) { this.picId = picId; } }
第三步,在activity的布局文件里
设置如下图所示 第一个画红色线的是布局文件里需要的,下面两个是给自定义的UpEditText定义自己增加取消按钮的属性值
然后再activity中添加代码
搞定
参考别人代码:
https://github.com/opprime/EditTextField(该代码是基于以前老的sdk写的)