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

[Android] 自定義帶清除按鈕的 EditText 完整實作

編輯:關於 Android 程式設計

帶一鍵清除功能的輸入框,幾乎每個 App 的搜尋欄都會用到。自己實作一次,可以順便把「複合 Drawable」「TextWatcher」「焦點監聽」這三個基礎 API 串起來。

要解決的問題拆成五項:

a) 建立自定義 EditText 類
b) 在 EditText 中顯示清除圖示
c) 依輸入內容顯示或隱藏圖示
d) 點擊圖示時清空文字並隱藏圖示
e) 依焦點的得失切換圖示

a) 建立 MyClearEditText

public MyClearEditText(Context context) {
    this(context, null);
}

public MyClearEditText(Context context, AttributeSet attrs) {
    this(context, attrs, android.R.attr.editTextStyle);
}

public MyClearEditText(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

三個構造方法都要覆寫,因為 XML 膨脹時系統只會呼叫帶 AttributeSet 的那一個。

b) 顯示清除圖示

要在文字的四個方向放圖,用 setCompoundDrawables 或 setCompoundDrawablesWithIntrinsicBounds。這裡採用後者,因為它會依圖片本身尺寸計算,不必手動指定大小。

/** 初始化清除的圖片 */
private void initClearDrawable() {
    draw = getCompoundDrawables()[2];   // 先取右側既有圖片
    if (draw == null) {
        draw = getResources().getDrawable(R.drawable.editdelete);
    }
    // 初始狀態先不顯示
    this.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
}

結果如下:

c) 依內容切換顯示

實作 TextWatcher 並註冊監聽:

this.addTextChangedListener(this);

@Override
public void onTextChanged(CharSequence text, int start,
                          int lengthBefore, int lengthAfter) {
    if (text.length() > 0) {
        this.setCompoundDrawablesWithIntrinsicBounds(null, null, draw, null);
    } else {
        this.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
    }
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

@Override
public void afterTextChanged(Editable s) { }

d) 判斷是否點到清除圖示

清除圖示不是獨立控件,無法單獨掛 OnClickListener。解法是攔截觸摸事件,用點擊的 x 座標判斷是否落在右側 padding 區域內:

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_UP) {
        // 觸點落在「右側自訂圖示」的範圍內
        if (event.getX() > (getWidth() - getTotalPaddingRight())
                && event.getX() < (getWidth() - getPaddingRight())) {
            setText("");
        }
    }
    return super.onTouchEvent(event);
}

e) 焦點變化時的處理

只做到這裡還有個 bug:畫面上有兩個輸入框時,在 A 框輸入文字後點到 B 框,A 框的清除圖示仍然掛著。因為圖示顯示與否應該跟焦點綁定,所以要再覆寫 onFocusChanged:

@Override
protected void onFocusChanged(boolean focused, int direction,
                             Rect previouslyFocusedRect) {
    super.onFocusChanged(focused, direction, previouslyFocusedRect);
    if (focused && !this.getText().toString().equals("")) {
        this.setCompoundDrawablesWithIntrinsicBounds(null, null, draw, null);
    } else {
        this.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
    }
}

完整程式碼

package com.xiaoyan.xiaoyanlibrary.common.widget.edittext;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.EditText;

/**
 * 自定義一個具有清除功能的 EditText
 */
public class MyClearEditText extends EditText implements TextWatcher {

    /** 儲存清除的圖片 */
    private Drawable draw;

    public MyClearEditText(Context context) {
        this(context, null);
    }

    public MyClearEditText(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.editTextStyle);
    }

    public MyClearEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initClearDrawable();
        this.addTextChangedListener(this);
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction,
                                 Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        if (focused && !this.getText().toString().equals("")) {
            this.setCompoundDrawablesWithIntrinsicBounds(null, null, draw, null);
        } else {
            this.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        }
    }

    /** 初始化清除的圖片 */
    private void initClearDrawable() {
        draw = getCompoundDrawables()[2];
        if (draw == null) {
            draw = getResources().getDrawable(R.drawable.editdelete);
        }
        this.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
    }

    @Override
    public void onTextChanged(CharSequence text, int start,
                             int lengthBefore, int lengthAfter) {
        if (text.length() > 0) {
            this.setCompoundDrawablesWithIntrinsicBounds(null, null, draw, null);
        } else {
            this.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

    @Override
    public void afterTextChanged(Editable s) { }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (event.getX() > (getWidth() - getTotalPaddingRight())
                    && event.getX() < (getWidth() - getPaddingRight())) {
                setText("");
            }
        }
        return super.onTouchEvent(event);
    }
}

還有兩個可以再加強的地方:一是點擊圖示時最好判斷一下 draw 是否為 null(未顯示時不該觸發清空);二是 getCompoundDrawables()[2] 在 API 17 之前需要改用 getCompoundDrawables()[2] 的舊版 API 對應寫法,並注意 RTL 布局下清除圖示應該放在左側。若追求更簡潔的實作,直接改用 TextInputLayout 搭配自定義 suffix icon,可以省下這整套座標判斷。

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