效果圖:

GIF.gif
1. 編寫xml布局 代碼 如下:
<com.zjq.cleareditextview.ClearEditTextView
android:id="@+id/et_username"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_marginTop="5dp"
android:hint="QQ號(hào)/手機(jī)號(hào)/郵箱號(hào)"
android:inputType="number"
android:lines="1"
android:maxLength="17"
android:paddingLeft="13dp"
android:textColorHint="#b9b7b7"
android:textSize="16sp" />
注意這里的 com.zjq.clearedittextview.ClearEditTextView 要與你的 ClearEditTextView類包名相同
2.創(chuàng)建ClearEditTextView類并繼承EditText
public class ClearEditTextView extends EditText implements View.OnFocusChangeListener,TextWatcher {
// 右邊的刪除按鈕
private Drawable mClearDrawable;
public ClearEditTextView(Context context) {
this(context, null);
}
public ClearEditTextView(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.editTextStyle);
}
public ClearEditTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
//獲取右邊刪除按鈕
mClearDrawable = getResources().getDrawable(R.drawable.delete_selector);
//設(shè)置刪除按鈕的邊界
mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight());
//設(shè)置默認(rèn)隱藏刪除按鈕
setClearIcon(false);
//監(jiān)聽(tīng)EditText焦點(diǎn)變化 ,根據(jù)text長(zhǎng)度控制刪除按鈕的顯示 .隱藏
setOnFocusChangeListener(this);
//監(jiān)聽(tīng)文本內(nèi)容變化
addTextChangedListener(this);
}
/**
* 控制EditText右邊制刪除按鈕的顯示、隱藏
*/
/**
* 控制EditText右邊制刪除按鈕的顯示、隱藏
*/
private void setClearIcon(boolean isShow) {
Drawable rightDrawable = isShow ? mClearDrawable : null;
setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1],
rightDrawable, getCompoundDrawables()[3]);
} }
注意這里的R.drawable.delete_selector。
3.在miamap下面放入兩張刪除圖片
一張是默認(rèn)顯示的圖片
命名為:search_clear_normal.png
一張是按下刪除按鈕顯示的圖片
命名為:search_clear_pressed
4.在drawable文件下創(chuàng)建delete_selector.xml文件
<?xml version="1.0" encoding="utf-8"?>
< selector xmlns:android="http://schemas.android.com/apk/res/android">
<!--按下?tīng)顟B(tài)-->
<item android:state_pressed="true" android:drawable="@mipmap/search_clear_pressed" />
<!--默認(rèn)顯示-->
<item android:drawable="@mipmap/search_clear_normal" />
</selector>