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

EditText 輸入監聽與表單驗證:可複用的 TextWatcher 設計

編輯:關於 Android 程式設計

Android design support 包提供了一種在輸入不合法時持續顯示提示的方式,如今已被越來越多應用採用。不過各家 App 呈現錯誤提示的手法五花八門,放在一起看總讓人覺得不夠協調。而 TextInputLayout 裡那圈環繞 EditText 的錯誤訊息,順帶還附贈了 Material 風格中活潑的浮動標籤——這在許多 App 裡往往是使用者體驗最平淡的環節之一。

接下來示範如何打造一個通用、可重複使用的元件來處理所有欄位驗證。核心需求是:使用者修正錯誤後,提示要自動消失。這可以靠 TextWatcher 達成。

要提醒的是,在 support library 23.1 中,隱藏錯誤提示後再次顯示會有 bug,因此以下範例建立在 23.0.1 版本上。

建立通用基底類別

先寫一個實作 TextWatcher 的抽象類 ErrorTextWatcher。為了簡化,我們假設每個 watcher 都對應一個 TextInputLayout,且只顯示一則錯誤訊息(實務上你可能需要「密碼不能為空」、「至少包含一個數字」等多種提示)。

 public abstract class ErrorTextWatcher implements TextWatcher { private TextInputLayout mTextInputLayout; private String errorMessage; protected ErrorTextWatcher(@NonNull final TextInputLayout textInputLayout, @NonNull final String errorMessage) { this.mTextInputLayout = textInputLayout; this.errorMessage = errorMessage; } 

再補上幾個通用方法:

 public final boolean hasError() { return mTextInputLayout.getError() != null; } protected String getEditTextValue() { return mTextInputLayout.getEditText().getText().toString(); } 

所有子類都要實作 validate(),輸入正確時回傳 true,如此一來顯示與隱藏錯誤只需一行:

 public abstract boolean validate(); protected void showError(final boolean error) { if (!error) { mTextInputLayout.setError(null); mTextInputLayout.setErrorEnabled(false); } else { if (!errorMessage.equals(mTextInputLayout.getError())) { // Stop the flickering that happens when setting the same error message multiple times mTextInputLayout.setError(errorMessage); } mTextInputLayout.requestFocus(); } } 

這裡有兩個實務上踩過的坑。第一,只把 setErrorEnabled(false) 是不夠的——EditText 的下劃線仍會維持錯誤顏色,所以必須同時把錯誤文字設為 null。第二,若每次都重設同一段錯誤字串,提示會伴隨動畫不斷閃爍,因此要先比對現值,只在內容有異時才寫入。

另外我在 onTextChanged 中集中處理所有邏輯,並在父類為 beforeTextChanged 與 afterTextChanged 補上空的實作,讓子類不必被無關的方法干擾。

案例一:最小長度驗證

最常見的需求莫過於「至少 x 個字元」。實作 MinimumLengthTextWatcher,帶一個最小長度參數:

 public class MinimumLengthTextWatcher extends ErrorTextWatcher { private final int mMinLength; private boolean mReachedMinLength = false; public MinimumLengthTextWatcher(final TextInputLayout textInputLayout, final int minLength) { this(textInputLayout, minLength, R.string.error_too_few_characters); } public MinimumLengthTextWatcher(final TextInputLayout textInputLayout, final int minLength, @StringRes final int errorMessage) { super(textInputLayout, String.format(textInputLayout.getContext().getString(errorMessage), minLength)); this.mMinLength = minLength; } 

提供兩個建構子:一個用預設訊息,一個允許指定專屬文案。為了支援多語,這裡一律使用 Android 字串資源而非硬編碼。

 @Override public void onTextChanged(final CharSequence text…) { if (mReachedMinLength) { validate(); } if (text.length() >= mMinLength) { mReachedMinLength = true; } } @Override public boolean validate() { mReachedMinLength = true; // This may not be true but now we want to force the error to be shown showError(getEditTextValue().length() < mMinLength); return !hasError(); } 

mReachedMinLength 這個旗標是體驗上的關鍵:使用者還沒打滿最小字數之前不該被叨唸,只有在他曾經達到門檻又刪到不足時,才提示錯誤。否則才剛點進欄位就看到紅字,是相當糟糕的第一印象。

掛上監聽:

 mPasswordView = (TextInputLayout) findViewById(R.id.password_text_input_layout); mValidPasswordTextWatcher = new MinimumLengthTextWatcher(mPasswordView, getResources().getInteger(R.integer.min_length_password)); mPasswordView.getEditText().addTextChangedListener(mValidPasswordTextWatcher); 

需要時隨處查詢結果:

 boolean isValid = mValidPasswordTextWatcher.validate();

若無效,該 View 會自動取得焦點並讓螢幕捲動過去。

案例二:Email 格式驗證

另一個常見需求是檢查信箱格式。用正則表達式驗證 email 本身就是個有爭議的話題,寫一整篇都講不完,因此我把驗證邏輯從 watcher 中抽離成獨立、可測試的 EmailAddressValidator,你可以直接沿用,也可以換成自己的實作。

 public class ValidEmailTextWatcher extends ErrorTextWatcher { private final EmailAddressValidator mValidator = new EmailAddressValidator(); private boolean mValidated = false; public ValidEmailTextWatcher(@NonNull final TextInputLayout textInputLayout) { this(textInputLayout, R.string.error_invalid_email); } public ValidEmailTextWatcher(@NonNull final TextInputLayout textInputLayout, @StringRes final int errorMessage) { super(textInputLayout, textInputLayout.getContext().getString(errorMessage)); } @Override public void onTextChanged(…) { if (mValidated) { validate(); } } @Override public boolean validate() { showError(!mValidator.isValid(getEditTextValue())); mValidated = true; return !hasError(); } 
 mEmailView = (TextInputLayout) findViewById(R.id.email_text_input_layout); mValidEmailTextWatcher = new ValidEmailTextWatcher(mEmailView); mEmailView.getEditText().addTextChangedListener(mValidEmailTextWatcher);

表單提交前的總驗證

註冊或登入表單通常在提交前要一次驗證所有欄位。由於每個 watcher 在驗證失敗時會自動抓焦點,我習慣由下往上驗證,讓最後停在表單中最上面那個出錯的欄位:

 private boolean allFieldsAreValid() { /** * Since the text watchers automatically focus on erroneous fields, do them in reverse order so that the first one in the form gets focus * &= may not be the easiest construct to decipher but it's a lot more concise. It just means that once it's false it doesn't get set to true */ boolean isValid = mValidPasswordTextWatcher.validate(); isValid &= mValidEmailTextWatcher.validate(); return isValid; }

&= 的巧妙之處在於:一旦結果變成 false,後續就無法再被設回 true,同時又保證每個 validate 都會被執行到(不會像 && 那樣短路跳過)。

這套結構的價值在於可擴充:想加驗證規則,只要再寫一個繼承 ErrorTextWatcher 的子類,表單與 Activity 那邊完全不用改。

附錄:自帶清除按鈕的 ClearEditText

再補一個實用的小控件:在輸入框右側放一個小圖示,點一下清空內容。iOS 只要設定某個屬性就能做到,Android 原生 EditText 卻沒這功能,因此必須自己改寫。

思路並不複雜。我們可以用 android:drawableRight 在右側放圖:

困難在於 Android 不允許直接為 compound drawable 掛監聽。解法是攔 onTouchEvent 模擬點擊:在 ACTION_UP 時,若觸發位置落在「輸入框寬度 − 右側 padding」到「輸入框寬度 − 清除圖示寬度」之間,就判定為點中了清除鈕。

 package com.example.clearedittext; import android.content.Context; import android.graphics.drawable.Drawable; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.View.OnFocusChangeListener; import android.view.animation.Animation; import android.view.animation.CycleInterpolator; import android.view.animation.TranslateAnimation; import android.widget.EditText; public class ClearEditText extends EditText implements OnFocusChangeListener, TextWatcher { /** * 刪除按鈕的引用 */ private Drawable mClearDrawable; /** * 控件是否有焦點 */ private boolean hasFoucs; public ClearEditText(Context context) { this(context, null); } public ClearEditText(Context context, AttributeSet attrs) { //這裡構造方法也很重要,不加這個很多屬性不能再XML裡面定義 this(context, attrs, android.R.attr.editTextStyle); } public ClearEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { //獲取EditText的DrawableRight,假如沒有設置我們就使用默認的圖片 mClearDrawable = getCompoundDrawables()[2]; if (mClearDrawable == null) { // throw new NullPointerException("You can add drawableRight attribute in XML"); mClearDrawable = getResources().getDrawable(R.drawable.delete_selector); } mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight()); //默認設置隱藏圖標 setClearIconVisible(false); //設置焦點改變的監聽 setOnFocusChangeListener(this); //設置輸入框裡面內容發生改變的監聽 addTextChangedListener(this); } /** * 因為我們不能直接給EditText設置點擊事件,所以我們用記住我們按下的位置來模擬點擊事件 * 當我們按下的位置 在 EditText的寬度 - 圖標到控件右邊的間距 - 圖標的寬度 和 * EditText的寬度 - 圖標到控件右邊的間距之間我們就算點擊了圖標,豎直方向就沒有考慮 */ @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); } /** * 當ClearEditText焦點發生變化的時候,判斷裡面字符串長度設置清除圖標的顯示與隱藏 */ @Override public void onFocusChange(View v, boolean hasFocus) { this.hasFoucs = hasFocus; if (hasFocus) { setClearIconVisible(getText().length() > 0); } else { setClearIconVisible(false); } } /** * 設置清除圖標的顯示與隱藏,調用setCompoundDrawables為EditText繪制上去 * @param visible */ protected void setClearIconVisible(boolean visible) { Drawable right = visible ? mClearDrawable : null; setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]); } /** * 當輸入框裡面內容發生變化的時候回調的方法 */ @Override public void onTextChanged(CharSequence s, int start, int count, int after) { if(hasFoucs){ setClearIconVisible(s.length() > 0); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } /** * 設置晃動動畫 */ public void setShakeAnimation(){ this.setAnimation(shakeAnimation(5)); } /** * 晃動動畫 * @param counts 1秒鐘晃動多少下 * @return */ public static Animation shakeAnimation(int counts){ Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0); translateAnimation.setInterpolator(new CycleInterpolator(counts)); translateAnimation.setDuration(1000); return translateAnimation; } } 

幾個關鍵點:setClearIconVisible() 不是用 setVisibility()(那是 View 的方法),而是透過 setCompoundDrawables() 把右側 Drawable 換成 null 來達到隱藏;setShakeAnimation() 則是組合位移動畫與正弦式的 CycleInterpolator,讓輸入框左右抖動。

而 hasFoucs 這個判斷看似多餘,其實很重要。想想登入頁的情境:若已保存帳號密碼,onCreate() 會把值填進輸入框,文字變動進而觸發監聽,導致兩個欄位的清除鈕同時亮起——這顯然不是我們要的。加上焦點判斷後,只有正在編輯的欄位才會顯示清除鈕。

使用方式

 <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#95CAE4"> <com.example.clearedittext.ClearEditText android:id="@+id/username" android:layout_marginTop="60dp" android:layout_width="fill_parent" android:background="@drawable/login_edittext_bg" android:drawableLeft="@drawable/icon_user" android:layout_marginLeft="10dip" android:layout_marginRight="10dip" android:singleLine="true" android:drawableRight="@drawable/delete_selector" android:hint="輸入用戶名" android:layout_height="wrap_content" > </com.example.clearedittext.ClearEditText> <com.example.clearedittext.ClearEditText android:id="@+id/password" android:layout_marginLeft="10dip" android:layout_marginRight="10dip" android:layout_marginTop="10dip" android:drawableLeft="@drawable/account_icon" android:hint="輸入密碼" android:singleLine="true" android:password="true" android:drawableRight="@drawable/delete_selector" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/username" android:background="@drawable/login_edittext_bg" > </com.example.clearedittext.ClearEditText> <Button android:id="@+id/login" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dip" android:layout_marginRight="10dip" android:background="@drawable/login_button_bg" android:textSize="18sp" android:textColor="@android:color/white" android:layout_below="@+id/password" android:layout_marginTop="25dp" android:text="登錄" /> </RelativeLayout> 
 package com.example.clearedittext; import android.app.Activity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { private Toast mToast; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ClearEditText username = (ClearEditText) findViewById(R.id.username); final ClearEditText password = (ClearEditText) findViewById(R.id.password); ((Button) findViewById(R.id.login)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(TextUtils.isEmpty(username.getText())){ //設置晃動 username.setShakeAnimation(); //設置提示 showToast("用戶名不能為空"); return; } if(TextUtils.isEmpty(password.getText())){ password.setShakeAnimation(); showToast("密碼不能為空"); return; } } }); } /** * 顯示Toast消息 * @param msg */ private void showToast(String msg){ if(mToast == null){ mToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT); }else{ mToast.setText(msg); } mToast.show(); } } 

順帶一提,showToast() 之所以要保留同一個 Toast 實例並重設文字,是為了避免連續點擊時堆疊出一長串提示。至於 setShakeAnimation() 裡 CycleInterpolator 的參數代表一秒內來回次數,可依手感調整。

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