带删除的EditText

时间:2023-03-09 23:02:03
带删除的EditText

  在安卓开发中EditText是比较常用的控件之一,那我们平常看到EditText填写了内容之后右边会出现一个删除的按钮,这样可以方便用户对其中文本清空操作,是非常人性化的,我们可以重写EditText来达到这样的效果。代码很简单,需要的盆友直接考皮就可以用,注意里面引用到一个删除按钮的图片资源。

package com.android.app;

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.view.View;
import com.android.app.R; public class EditText extends android.widget.EditText implements View.OnFocusChangeListener { private Drawable mDeleteIcon;
private Context mContext; public EditText(Context context) {
super(context);
mContext = context;
init();
} public EditText(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
init();
} public EditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
init();
} private void init() {
this.setOnFocusChangeListener(this);
mDeleteIcon = mContext.getResources().getDrawable(R.drawable.ic_input_close);
if (this.length() > 0) {
setCompoundDrawablesWithIntrinsicBounds(null, null, mDeleteIcon, null);
}
this.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();
}
});
} // 设置删除图片
private void setDrawable() {
if (this.length() > 0)
setCompoundDrawablesWithIntrinsicBounds(null, null, mDeleteIcon, null);
else
setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
} @Override
public void onFocusChange(View view, boolean b) {
if (!b)
setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
else
setDrawable();
} // 处理删除事件
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mDeleteIcon != 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 - 50;
if (rect.contains(eventX, eventY))
setText("");
}
return super.onTouchEvent(event);
} @Override
protected void finalize() throws Throwable {
super.finalize();
}
}