package cn.mobile.renrentou.main.view.edittext;
import cn.mobile.renrentou.R;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.EditText;
public class CustomEditText extends EditText {
private Drawable dRight;
private boolean dismissHintOnFocus = false;
public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.initAttrs(context, attrs);
}
public CustomEditText(Context context, AttributeSet attrs) {
super(context, attrs);
this.initAttrs(context, attrs);
}
public CustomEditText(Context context) {
super(context);
}
@SuppressLint("Recycle")
private void initAttrs(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomEditText);
dismissHintOnFocus = typedArray.getBoolean(R.styleable.CustomEditText_dismissHintOnFocus, true);
}
@Override
public void setCompoundDrawables(Drawable left, Drawable top,
Drawable right, Drawable bottom) {
if (right != null) {
dRight = right;
}
super.setCompoundDrawables(left, top, right, bottom);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP && dRight != null) {
final int x = (int) event.getX();
final int y = (int) event.getY();
// check to make sure the touch event was within the bounds of the
int w = getWidth();
if (x <= w - this.getPaddingRight()
&& x >= (w - this.getPaddingRight() - dRight
.getIntrinsicWidth())) {
this.setText("");
// use this to prevent the keyboard from coming up
event.setAction(MotionEvent.ACTION_CANCEL);
}
}
return super.onTouchEvent(event);
}
@Override
protected void onFocusChanged(boolean focused, int direction,
Rect previouslyFocusedRect) {
Log.d("CustomEdit", "onFocusChaged: " + dismissHintOnFocus);
if (!dismissHintOnFocus) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
return;
}
String hint;
if (focused) {
CharSequence cs = this.getHint();
cs = (cs == null) ? "" : cs;
hint = cs.toString();
if (null != hint && !"".equals(hint)) {
this.setTag(hint);
this.setHint("");
} else {
this.setTag("");
}
} else {
hint = this.getTag().toString();
this.setHint(hint);
}
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
@Override
protected void finalize() throws Throwable {
dRight = null;
super.finalize();
}
}
内容很单一,参考别人的成品,但是报大量错误,经过修改后调试出在我的项目中不报错的版本,应用需要声明attrs属性,dismissHintOnFocus, 右侧x图片则声明drawableRight 可能 有许多冗余代码和bug,大家根据自己的应用自己调试即可。如果有错误或者有其他想法思路,请大家留言不吝赐教。尽量不要用wrap_content标记宽度。