編輯:Android 開發實例
iOS 的 UITextField 只要打開一個屬性就有清除按鈕,Android 原生的 EditText 卻沒有現成方案。要補上這個功能,只能自己動手改。本文實作一個 ClearEditText:輸入框右側顯示小叉,點一下就清空內容,同時附贈一個「輸入錯誤時左右抖動」的小動畫。

EditText 可以透過 android:drawableRight 在右側放一張圖,問題是這張圖並沒有獨立的點擊事件。解法是自己攔下 onTouchEvent:在 ACTION_UP 的瞬間比對觸發位置,若落在「輸入框寬度 − 右側內距 − 圖示寬度」到「輸入框寬度 − 右側內距」之間,就判定使用者點了清除鈕。這個判斷只處理水平方向,垂直方向不額外計較,實測已經夠用。
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 {
/** 清除按鈕的 Drawable */
private Drawable mClearDrawable;
/** 是否已取得焦點 */
private boolean hasFoucs;
public ClearEditText(Context context) {
this(context, null);
}
/** 少了這個建構子,XML 上的屬性會無法套用 */
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);
init();
}
private void init() {
// 抓取 EditText 的右側 Drawable;若 XML 沒設就退回預設圖示
mClearDrawable = getCompoundDrawables()[2];
if (mClearDrawable == null) {
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);
}
/** 焦點改變時決定清除圖示的顯示與否 */
@Override public void onFocusChange(View v, boolean hasFocus) {
this.hasFoucs = hasFocus;
if (hasFocus) {
setClearIconVisible(getText().length() > 0);
} else {
setClearIconVisible(false);
}
}
/** 透過 setCompoundDrawables 重畫四邊圖示來控制顯示與隱藏 */
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 每秒晃動次數
*/
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 的;我們要控制的只是四邊其中一個 Drawable,改用 setCompoundDrawables(left, top, right, bottom) 才對。
setOnFocusChangeListener(this):有焦點時才檢查內容長度,空字串就隱藏圖示,否則顯示。
addTextChangedListener(this):內容變動時依長度切換圖示,但必須額外判斷焦點。原因很實際——登入頁若已記住帳密,在 onCreate() 把值填進輸入框時會觸發 text changed,若沒有焦點判斷,兩個欄位的清除鈕就會一起冒出來,那不是我們想要的行為。
setShakeAnimation():用 TranslateAnimation 搭配 CycleInterpolator,讓位移量呈正弦曲線來回擺盪,就能做出左右抖動的效果。這個小細節在輸入錯誤時特別好用。
兩個自訂輸入框加一顆登入鈕,右側圖示透過 android:drawableRight 指定:
<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>
按下登入時先檢查欄位,空白就抖一下並提示,順便示範如何重複使用同一個 Toast 物件避免閃爍。
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,避免連續提示時閃動 */
private void showToast(String msg) {
if (mToast == null) {
mToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
} else {
mToast.setText(msg);
}
mToast.show();
}
}
執行結果如下:

ClearEditText 是個很值得放進工具庫的小元件,除了登入頁,任何需要快速清空的重搜尋框、表單欄位都適用;而抖動動畫搭配表單驗證使用,回饋感也比單純跳一則 Toast 來得直接。
Android 音樂播放器實作:MediaPlayer 搭配 SeekBar 的完整流程
Android 想播放一段音訊或影片,最直接的入口就是 MediaPlayer。它站在系統的媒體播放服務之上,把解碼、音訊輸出這些底層細節都收 ourselves 起來,
Android 本地化實作:文字、數字與資源的區域適配
Android App 可能同時運行在不同國家、不同語言環境的裝置上。要讓應用更具親和力,就必須處理文字、數字、檔案等內容在各地區的呈現差異。 本章說明如何依不同區域對
Android 圖片特效:黑白、圓角與高斯模糊
在 Android 中處理圖片特效,可以透過 Bitmap 與 Canvas 完成多種常見效果。黑白效果通常是讀取每個像素的 RGB 值,再以加權方式轉成灰階,最後重新組
動手做「開發者頭條」App(四):用 Design Support Library 重寫首頁
一、前言 上一版首頁做出來之後,拿給身邊的產品經理看,得到的評價是:功能對了,技術還是上一代的寫法。於是花了幾天把 design 包整個翻了一遍,把首頁代碼近乎重寫,順便