EditText的四周可以设置drawable,在xml中通过drawabLeft,drawabTop,drawabRight,drawabBottom设置。
在代码中可以通过setCompoundDrawablesWithIntrinsicBounds(left,top,right,bottom)设置,
通过getCompoundDrawables()返回一个Drawable[] ,对应4个位置的drawable。
当drawable被点击,对点击事件的处理,通过在onTouchEvent()里处理。
对EditText添加TextChangeListener,当文本length大于1时显示del按钮。
public class EditTextWithDel extends EditText{
private Context mContext;
private Drawable imgInable;
private Drawable imgAble;
private String TAG = "EditTextWithDel";
public EditTextWithDel(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
mContext = context;
init();
}
public EditTextWithDel(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
mContext = context;
init();
}
public EditTextWithDel(Context context) {
super(context);
// TODO Auto-generated constructor stub
mContext = context;
init();
}
private void init() {
imgInable = mContext.getResources().getDrawable(R.drawable.delete_gray);
imgAble = mContext.getResources().getDrawable(R.drawable.delete);
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();
}
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();
Log.e(TAG , "eventX = " + eventX + "; eventY = " + eventY);
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();
}
}