public class MyEditText extends EditText{
private Context mContext;
private Drawable drawable;
private Drawable bgDrawable;
public MyEditText(Context context) {
super(context);
mContext = context;
init();
}
public MyEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
init();
}
public MyEditText(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
init();
}
private void init(){
setBackgroundResource(R.drawable.shape_my_edit);
drawable = mContext.getResources().getDrawable(R.drawable.delete);
bgDrawable = mContext.getResources().getDrawable(R.drawable.login_ok);
addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
setDrawable();
}
@Override
public void afterTextChanged(Editable s) {}
});
}
private void setDrawable(){
if(length() < 1){
setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);
}else if(length() == 11){
setCompoundDrawablesWithIntrinsicBounds(null,null, bgDrawable,null);
}else{
setCompoundDrawablesWithIntrinsicBounds(null,null, drawable,null);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (drawable != 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);
}
}
效果图见附件