編輯:關於 Android 程式設計
帶一鍵清除功能的輸入框,幾乎每個 App 的搜尋欄都會用到。自己實作一次,可以順便把「複合 Drawable」「TextWatcher」「焦點監聽」這三個基礎 API 串起來。
要解決的問題拆成五項:
a) 建立自定義 EditText 類
b) 在 EditText 中顯示清除圖示
c) 依輸入內容顯示或隱藏圖示
d) 點擊圖示時清空文字並隱藏圖示
e) 依焦點的得失切換圖示
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 的那一個。
要在文字的四個方向放圖,用 setCompoundDrawables 或 setCompoundDrawablesWithIntrinsicBounds。這裡採用後者,因為它會依圖片本身尺寸計算,不必手動指定大小。
/** 初始化清除的圖片 */
private void initClearDrawable() {
draw = getCompoundDrawables()[2]; // 先取右側既有圖片
if (draw == null) {
draw = getResources().getDrawable(R.drawable.editdelete);
}
// 初始狀態先不顯示
this.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
}
結果如下:

實作 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) { }
清除圖示不是獨立控件,無法單獨掛 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);
}
只做到這裡還有個 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,可以省下這整套座標判斷。
Android 插件化思考:仿 QQ 的一鍵換膚是怎麼跑起來的
群裡有朋友希望寫一篇關於插件化的文章。老實說我也談不上精通,那就從最樸素的思路出發,試著把「一鍵換膚」做出來——思路往往比程式碼更值得聊。 QQ 的換膚細節我並不清楚,但
深入理解 Activity 啟動流程:從點擊圖示到 onCreate
概要:一場跨三個行程的接力 使用者在 Launcher 上點一下應用圖示,看似簡單的動作,背後其實是好幾個行程之間的精密協作。 Android 系統中有一個 zygote
一個 Activity 的顯示過程總結(四):measure、layout、draw 源碼全流程
上一篇我們停在 ViewRootImpl 的三個關鍵方法上:performMeasure(測量)、performLayout(布局)、performDraw(繪製)。這次
ImageView 圖像控件詳解(上):屬性辨析與縮放模式
(一)概述 ImageView 是最基礎的圖像顯示控件,除了展示圖片,還支持放大、縮小、旋轉等操作。本篇先把它的幾個核心屬性掰扯清楚。 (二)src 與 backgro