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

Android 為 EditText 的 drawableRight 加上點擊事件

編輯:關於 Android 程式設計

在輸入框右側放一個「清除」或「搜尋」小圖示是很常見的設計,但官方 API 並沒有提供直接監聽 compound drawable 點擊的方法。實務上的解法是攔截 onTouch,再用 X 座標判斷手指是否落在圖示上。

這套寫法是通用的,不只 EditText,TextView、AutoCompleteTextView 等支援 compound drawable 的控制項都能套用。

版面檔

<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.drablerighttest.MainActivity" >

    <EditText android:id="@+id/et"
        android:layout_width="350dp"
        android:layout_height="wrap_content"
        android:drawableRight="@drawable/search_clear_pressed"
        android:text="@string/hello_world" />
</RelativeLayout>

MainActivity.java

public class MainActivity extends Activity {
    private EditText et;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et = (EditText) this.findViewById(R.id.et);

        et.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // getCompoundDrawables() 回傳長度為 4 的陣列,
                // 分別代表左、上、右、下四張圖片,索引 2 就是右邊
                Drawable drawable = et.getCompoundDrawables()[2];

                // 右邊沒有圖片就不處理
                if (drawable == null) return false;

                // 只在按下並抬起(ACTION_UP)時處理,避免觸發兩次
                if (event.getAction() != MotionEvent.ACTION_UP) return false;

                // 判斷 X 座標是否落在圖示範圍內
                if (event.getX() > et.getWidth()
                        - et.getPaddingRight()
                        - drawable.getIntrinsicWidth()) {
                    et.setText("");
                }
                return false;
            }
        });
    }
}

幾個容易踩到的細節

  • 一定要 return false。回傳 true 會把事件吃掉,導致游標無法正常定位、文字無法選取。回傳 false 表示「我處理完了但事件繼續往下走」。
  • 用 getIntrinsicWidth() 而不是 getBounds().width()。兩者都能算,但 intrinsic 尺寸才是圖示實際配置的大小,遇上 scaleType 或 NinePatch 時更準確。
  • 記得扣掉 getPaddingRight()。否則在設定了內距的輸入框上,判定範圍會偏移,導致點了圖示卻沒反應。
  • 先檢查 drawable 是否為 null。若版面沒設 drawableRight,getCompoundDrawables()[2] 會是 null,直接取寬度會丟 NullPointerException。
  • 圖示建議用 selector。準備 normal 與 pressed 兩張圖做成 StateListDrawable,點擊時視覺回饋會更明確。

掌握這個「座標比對」的套路之後,實作「有內容才顯示清除按鈕」、「點擊切換密碼明文/密文」這類互動都只是在此基礎上加條件判斷而已。

以上就是為 EditText 右側圖示掛上點擊事件的完整做法,希望對大家的學習有所幫助。

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