Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自定義 ClearEditText:為輸入框加上一鍵清空按鈕

編輯:關於 Android 程式設計

公司產品陸續在升級,這輪任務是優化程式碼結構與專案架構,於是開始全專案找冗餘。

先說需求場景。基本上每個 App 都有登入頁,登入頁少不了輸入框。當使用者發現內容打錯或想重來時,得一枚一枚按刪除鍵,體驗很差。理想情況是右側有個小圖標,點一下就清空——QQ 登入頁就是這個做法:

點密碼框右側的小叉,內容立刻清空。

專案裡其實早就自定義過這個控制項,一直用得好好的:

舊版的做法是一個 RelativeLayout 裡塞兩個 ImageView 夾一個 EditText,點右側那顆就清空。功能沒問題,但這次做代碼優化時發現:EditText 本來就有 drawableLeft 和 drawableRight,幹嘛還要額外疊兩層 ImageView?於是在草稿紙上重新畫了一版,程式碼量明顯精簡。

新版工程結構:

ClearEditText 繼承 EditText,正是為了沿用它的 compound drawable 屬性。

實作

 public class ClearEditText extends EditText implements TextWatcher, OnFocusChangeListener { /** 左右兩側圖片資源 */ private Drawable left, right; /** 是否獲取焦點,默認沒有焦點 */ private boolean hasFocus = false; /** 手指抬起時的X坐標 */ private int xUp = 0; public ClearEditText(Context context) { this(context, null); } public ClearEditText(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.editTextStyle); } public ClearEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initWedgits(); } /** 初始化各組件 */ private void initWedgits() { try { // 如果在布局文件中沒有定義drawableLeft屬性,則此值為空 left = getCompoundDrawables()[0]; right = getCompoundDrawables()[2]; initDatas(); } catch (Exception e) { e.printStackTrace(); } } /** 初始化數據 */ private void initDatas() { try { // 第一次顯示,隱藏刪除圖標 setCompoundDrawablesWithIntrinsicBounds(left, null, null, null); addListeners(); } catch (Exception e) { e.printStackTrace(); } } /** 添加事件監聽 */ private void addListeners() { try { setOnFocusChangeListener(this); addTextChangedListener(this); } catch (Exception e) { e.printStackTrace(); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int after) { if (hasFocus) { if (TextUtils.isEmpty(s)) { setCompoundDrawablesWithIntrinsicBounds(left, null, null, null); } else { if (null == right) { right = getCompoundDrawables()[2]; } setCompoundDrawablesWithIntrinsicBounds(left, null, right, null); } } } @Override public boolean onTouchEvent(MotionEvent event) { try { switch (event.getAction()) { case MotionEvent.ACTION_UP: xUp = (int) event.getX(); // 點擊位置到右側距離小於等於getCompoundPaddingRight()時,視為點擊了刪除圖標 if ((getWidth() - xUp) <= getCompoundPaddingRight()) { if (!TextUtils.isEmpty(getText().toString())) { setText(""); } } break; default: break; } } catch (Exception e) { e.printStackTrace(); } return super.onTouchEvent(event); } @Override public void afterTextChanged(Editable s) { } @Override public void onFocusChange(View v, boolean hasFocus) { try { this.hasFocus = hasFocus; } catch (Exception e) { e.printStackTrace(); } } } 

執行順序是這樣的:初始化時先從 getCompoundDrawables() 取出佈局裡設定的左右圖示(沒設定就是 null),然後把右側暫時藏起來。接著掛上兩個監聽器——OnFocusChangeListener 負責記錄焦點狀態存進 hasFocus,TextWatcher 則在內容變化時被觸發,依序走 beforeTextChanged、onTextChanged、afterTextChanged。我們只需要在 onTextChanged 裡判斷:有焦點且內容非空就顯示清除圖示,否則隱藏。

顯示與隱藏都靠 setCompoundDrawablesWithIntrinsicBounds(),它會按給定的圖示尺寸把圖畫到控制項的四個方向,傳 null 的那一側就不畫。

接下來是監聽清除圖示的點擊。原本直覺是給它掛 OnClickListener 或 OnTouchListener,但查過 API 之後發現 EditText 並未提供對 compound drawable 的點擊事件。自己寫一套監聽器當然可行,只是又把手續複雜化了。仔細想想,EditText 間繼承自 View,而 View 有 onTouchEvent()——重寫它,在裡面判斷手指抬起位置即可:若點擊位置到控制項右側的距離小於等於 getCompoundPaddingRight(),就認定點到了清除圖示。

這個方法的文件說明是:Returns the right padding of the view, plus space for the right Drawable if any——也就是右側 padding 加上右側圖示佔用的寬度,正好是清除鈕的可點擊範圍。

佈局與使用

用法和原本的 EditText 幾乎一樣,寫上完整包名即可:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ffffff"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="10dip" android:text="@string/hello" android:gravity="center" android:textSize="20sp" android:textColor="#000000" /> <com.llew.e.clear.view.wedgit.ClearEditText android:id="@+id/clearEditText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="10dip" android:paddingRight="8dip" android:paddingTop="5dip" android:paddingBottom="5dip" android:hint="請輸入QQ號碼" android:background="@drawable/pay_widget_input" android:drawableLeft="@drawable/super_qq" android:drawableRight="@drawable/clear_normal_list" /> </LinearLayout> 

Activity 那邊完全不用動,系統產生的樣板就夠了:

 public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } 

效果預覽:

輸入前:

輸入後:

點擊清除圖示後:

效果和舊版一致,程式碼卻精簡不少——這正是繼承機制帶來的好處。

實作上有兩處可以再打磨:一是 onTouchEvent 中的邊界判斷用的是 <=,當使用者點擊右側 padding 區域也會觸發清空,若覺得靈敏度太高,可以改成乘上一個係數收窄範圍;二是 setText("") 會觸發 TextWatcher 再次進入 onTextChanged,這裡因為空字串會走到隱藏分支,所以不會有迴圈問題,但類似結構在別的場景下要留意重入。

源碼下載:Android UI 實現帶清除功能的輸入框

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved