首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android EditText 右側嵌入可點擊圖標的完整實現

     編輯:程式設計綜合問答

在登錄頁、搜尋框等場景中,常需在 EditText 右側放置可點擊的圖標(如顯示/隱藏密碼、清空輸入、語音輸入)。Android 官方提供 drawableEnd / drawableRight 屬性,配合 OnTouchListener 即可實現交互。

核心代碼示例

<EditText
    android:id="@+id/et_password"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:drawableEnd="@drawable/ic_visibility_off"
    android:drawablePadding="12dp"
    android:inputType="textPassword" />

Java/Kotlin 點擊事件處理

editText.setOnTouchListener((v, event) -> {
    if (event.getAction() == MotionEvent.ACTION_UP) {
        int drawableEnd = editText.getCompoundDrawables()[2] != null ? 
            editText.getCompoundDrawables()[2].getBounds().width() : 0;
        if (event.getRawX() >= (editText.getRight() - drawableEnd - editText.getPaddingEnd())) {
            // 執行圖標點擊邏輯:切換密碼可見性、清空文字等
            return true; // 消費事件
        }
    }
    return false;
});

進階技巧

  • 使用 TextWatcher 動態顯示/隱藏清空圖標
  • 封裝為自定義 View 復用於多個輸入框
  • 搭配 TextInputLayout 實現 Material Design 風格

完整示例圖請參考原文附件截圖。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved