帶刪除按鈕的 EditText
一個帶刪除按鈕的 EditText 在各種 APP 中隨處可見,比如,搜尋框、登入時使用者名稱與密碼的輸入框等等。在沒有自己實現之前,想法是這樣的:在 EditText 中的新增一個 Drawable 然後給這個 Drawable 新增一個監聽事件,當點選 Drawable 時設定 EditText 裡的字串為空。當要實現的時候卻發現 Drawable 沒有點選事件,所以這個方法是行不通的。那麼只好通過觸控事件來實現,通過計算觸控的位置,這個位置正好就是該 Drawable 所在的位置。
獲取 EditText 的 DrawableRight
mClearDrawable = getCompoundDrawables()[2];
getCompoundDrawables() 方法原始碼是這樣的
/**
* Returns drawables for the left, top, right, and bottom borders.
*
* @attr ref android.R.styleable#TextView_drawableLeft
* @attr ref android.R.styleable#TextView_drawableTop
* @attr ref android.R.styleable#TextView_drawableRight
* @attr ref android.R.styleable#TextView_drawableBottom
*/
@NonNull
public Drawable[] getCompoundDrawables() {
final Drawables dr = mDrawables;
if (dr != null) {
return dr.mShowing.clone();
} else {
return new Drawable[] { null, null, null , null };
}
}
返回值是控制元件四周的 Drawable 陣列,順序為左、上、右、下。在這裡需要的是右邊的 Drawable,所以下標為 2.
2. 接下來就是獲取並設定 Drawable 圖示
if (mClearDrawable == null) {
mClearDrawable = getResources().getDrawable(R.drawable.x);
}
// 為 Drawable 設定為自身大小的寬高
mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight());
3.最後一步就是設定點選 Drawable 圖示實現刪除文字框中的內容
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP){
if (getCompoundDrawables()[2] != null){
boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight())
&& (event.getX() < (getWidth() - getPaddingRight()));
if (touchable){
this.setText("");
}
}
}
return super.onTouchEvent(event);
}
紅色的橫線代表的是 (getWidth() - getTotalPaddingRight())的值,黑色的橫線代表的是 (getWidth() - getPaddingRight()) 的值,當觸控到這兩個值之間的位置就正好是 Drawable 所在位置。也就實現了點選刪除圖示就可以清空文字框中的內容。
到此最主要功能就可以實現了,當然還可以再新增一些其他的功能,以提高使用者體驗。比如,當文字框中沒有內容時,就不顯示刪除圖示,或是在輸入錯誤時文字框抖動等。
首先實現刪除圖示的隱藏功能。
public void setClearIconVisible(boolean visible) {
Drawable right = visible ? mClearDrawable : null;
setCompoundDrawables(getCompoundDrawables()[0],getCompoundDrawables()[1],right,getCompoundDrawables()[3]);
}
setCompoundDrawables() 方法裡的四個引數就是按照左、上、右、下的順序分別為元件新增四個方向上的 Drawable。這裡新增的在右邊的,所以在第三個位置設定剛剛設定好的 Drawable。其他設定為預設的。然後實 TextWatcher 介面,在 onTextChange 方法裡進行設定。
public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
if (hasFocus){
setClearIconVisible(text.length() > 0);
}
}
接下來實現抖動功能。
public void setSharkAnimation(){
this.setAnimation(sharkAnimation(5));
}
public static Animation sharkAnimation(int counts){
Animation translateAnimation = new TranslateAnimation(0,10,0,0);
translateAnimation.setInterpolator(new CycleInterpolator(counts));
translateAnimation.setDuration(1000);
return translateAnimation;
}
在輸入錯誤或是有重要資訊時呼叫 setSharkAnimation() 方法就可以實現了。
最終效果圖:
總結
實現文章中的功能並不是很難,只要動動手基本都可以實現。所以重點是要動手去做,在沒有動手之前雖然也有很多的想法,想了幾種可能實現的方法,那些方法到底能不能實現,或是實現起來有什麼困難,亦或是可以更加簡潔等等,這些都不是隻靠想就可以做到的,所以以後再想到什麼想法的時候一定要親自動手實踐一下,再做結論。以上!