在开发Android应用程序时,有时需要EditText的的右侧提供一个删除按钮,当输入框有内容是显示右边的删除按钮,当输入框没有内容时隐藏右边的删除按钮。要实现这样的功能我们可以继承已有的EditText来实现,代码很简单,下面贴上代码:
public class LoginEditText extends EditText {
private Drawable mClearDrawble;
private Rect mBounds;
public LoginEditText(Context context) {
super(context);
initEditText();
}
public LoginEditText(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
initEditText();
}
public LoginEditText(Context context, AttributeSet attributeSet,int paramInt) {
super(context, attributeSet, paramInt);
initEditText();
}
private void initEditText() {
setEditTextDrawable();
addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable editable) {
}
@Override
public void beforeTextChanged(CharSequence charSequence,
int arg1, int arg2, int arg3) {
}
@Override
public void onTextChanged(CharSequence paramCharSequence,
int arg1, int arg2, int arg3) {
LoginEditText.this.setEditTextDrawable();
}
});
}
public void setEditTextDrawable() {
if (getText().toString().length() == 0) {
setCompoundDrawables(null, null, null, null);
} else {
setCompoundDrawables(null, null, mClearDrawble, null);
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mClearDrawble = null;
mBounds = null;
}
@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
if ((mClearDrawble != null) && (motionEvent.getAction() == MotionEvent.ACTION_UP)) {
mBounds = mClearDrawble.getBounds();
int i = (int) motionEvent.getRawX();
if (i > getRight() - 3 * mBounds.width()) {
setText("");
motionEvent.setAction(MotionEvent.ACTION_CANCEL);
}
}
return super.onTouchEvent(motionEvent);
}
@Override
public void setCompoundDrawables(Drawable left,Drawable top, Drawable right,Drawable bottom) {
if (right != null)
mClearDrawble = right;
super.setCompoundDrawables(left,top,right,bottom);
}
}
在布局文件中的使用如下:‘
<span style="color:#ff0000;"> <com.example.userlogin.LoginEditText</span>
android:id="@+id/account"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
<span style="color:#ff0000;"> android:drawableRight="@drawable/ic_clear_normal"</span>
android:background="@drawable/edit_text_selector"
android:ems="10"
android:inputType="textEmailAddress"
android:textColor="#ffffff" />
<span style="color:#ff0000;"> <com.example.userlogin.LoginEditText</span>
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="@drawable/edit_text_selector"
<span style="color:#ff0000;"> android:drawableRight="@drawable/ic_clear_normal"</span>
android:inputType="textPassword"
android:textColor="#ffffff" />