public class MyEditText extends EditText { private Drawable dRight; private Rect rRounds; public MyEditText(Context context) { super(context); // TODO Auto-generated constructor stub initEditText(); } public MyEditText(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub initEditText(); } public MyEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub initEditText(); } //初始化EditText private void initEditText(){ setEditTextDrawable(); addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub MyEditText.this.setEditTextDrawable(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }); } //控制图片的显示 private void setEditTextDrawable() { // TODO Auto-generated method stub if(getText().toString().length() == 0){ setCompoundDrawables(null, null, null, null); } else { setCompoundDrawables(null, null,this.dRight, null); } } @Override protected void onDetachedFromWindow() { // TODO Auto-generated method stub super.onDetachedFromWindow(); this.dRight = null; this.rRounds = null; } //添加触摸事件,点击之后出现清空效果 @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub if((this.dRight != null) && (event.getAction() == 1)){ this.rRounds = this.dRight.getBounds(); int i = (int)event.getRawX(); if(i>getRight() - 4 * this.rRounds.width()){ setText(""); event.setAction(MotionEvent.ACTION_CANCEL); } } return super.onTouchEvent(event); } //显示右侧删除图标 @Override public void setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom) { // TODO Auto-generated method stub if(right != null){ this.dRight = right; } super.setCompoundDrawables(left, top, right, bottom); } }
时间: 2024-10-11 23:05:16