Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

自製 ClearEditText:為 Android 輸入框加上一鍵清除

編輯:Android 開發實例

需求與思路

本文實作一個很實用的小控件 ClearEditText:在輸入框右側放一個小圖示,點一下就能清空內容。iOS 只要設定某個屬性就能做到,但 Android 原生 EditText 並不支援,因此必須自己繼承改寫。

關鍵在於,EditText 可以透過 android:drawableRight 在右側放圖:

思路很直接:如果能攔到「點擊右側圖示」這個事件,清空內容並隱藏圖示,功能就完成了。問題是 Android 並未提供給 compound drawable 掛監聽的接口。解法是用 onTouchEvent() 模擬點擊:當 ACTION_UP 發生的 x 座標落在「清除圖示左邊界到右邊界」之間,就判定為點擊了圖示。這裡暫不考慮垂直方向。

完整實作

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);
    }

    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 的右側 Drawable;若未設定則退回預設圖示
        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 無法直接為單一 compound 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);
    }

    /** 焦點改變時,依內容長度決定清除圖示的顯示 */
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        this.hasFoucs = hasFocus;
        setClearIconVisible(hasFocus && getText().length() > 0);
    }

    /** 透過 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));
    }

    /** 抖動動畫: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 的),而是用 setCompoundDrawables(left, top, right, bottom) 把右側圖示換成 Drawable 或 null,藉此達到顯示/隱藏的效果。

setOnFocusChangeListener(this):監聽焦點變化。取得焦點時判斷內容是否為空,空則隱藏圖示,否則顯示。

addTextChangedListener(this):監聽內容變化,內容非空就顯示清除圖示。這裡特意加上「必須有焦點」的條件——想想登入頁面的情境:若已保存帳號密碼並在 onCreate() 中回填,內容變化會讓兩個輸入框的清除圖示同時亮起,這顯然不是我們要的行為。

setShakeAnimation():左右抖動效果。有些 App 在帳號或密碼錯誤時會讓輸入框抖一下,回饋感很不錯。實作上就是一個平移動畫,再把變化率設為正弦曲線。

在使用頁面中引用

<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:layout_height="wrap_content"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:background="@drawable/login_edittext_bg"
        android:drawableLeft="@drawable/icon_user"
        android:drawableRight="@drawable/delete_selector"
        android:hint="輸入用戶名"
        android:singleLine="true" >
    </com.example.clearedittext.ClearEditText>

    <com.example.clearedittext.ClearEditText
        android:id="@+id/password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/username"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:layout_marginTop="10dip"
        android:background="@drawable/login_edittext_bg"
        android:drawableLeft="@drawable/account_icon"
        android:drawableRight="@drawable/delete_selector"
        android:hint="輸入密碼"
        android:password="true"
        android:singleLine="true" >
    </com.example.clearedittext.ClearEditText>

    <Button
        android:id="@+id/login"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/password"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:layout_marginTop="25dp"
        android:background="@drawable/login_button_bg"
        android:text="登錄"
        android:textColor="@android:color/white"
        android:textSize="18sp" />
</RelativeLayout>

Activity 端主要是測試抖動效果:

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();
    }
}

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