package com.example.administrator.newspolice.view; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.EditText; import com.example.administrator.newspolice.R; /** * @desc: 带删除按钮的editText */ @SuppressLint("AppCompatCustomView") public class EditTextWithDel extends EditText { /** * 删除的icon */ private Drawable imgAble; /** * 上下文 */ private Context mContext; public EditTextWithDel(Context context) { super(context); mContext = context; init(); } public EditTextWithDel(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mContext = context; init(); } public EditTextWithDel(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; init(); } /** * 初始化 * * @version 1.0 */ private void init() { imgAble = mContext.getResources().getDrawable(R.mipmap.ic_clear); addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { setDrawable(); } }); setDrawable(); } /** * 设置显示或隐藏删除图标 * * @version 1.0 */ private void setDrawable() { if (length() < 1){ setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); }else{ setCompoundDrawablesWithIntrinsicBounds(null, null, imgAble, null); } } @Override public boolean onTouchEvent(MotionEvent event) { if (imgAble != null && event.getAction() == MotionEvent.ACTION_UP) { int eventX = (int) event.getRawX(); int eventY = (int) event.getRawY(); Rect rect = new Rect(); getGlobalVisibleRect(rect); rect.left = rect.right - dip2px(mContext, 30); if (rect.contains(eventX, eventY)) { setText(""); return true; } } return super.onTouchEvent(event); } @Override protected void finalize() throws Throwable { super.finalize(); } /** * 根据手机的分辨率从 dp 的单位 转成为 px(像素) */ public static int dip2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } }