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

Android EditText 右側添加圖標:FrameLayout 包裹方案

     編輯:程式設計綜合問答

需求

在 EditText 或 TextView 最右側顯示一個圖標(如搜尋、清除、眼睛)。

最簡佈局


<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingRight="40dp" /> <!-- 留出圖標空間 -->

    <ImageView
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_gravity="center_vertical|end"
        android:layout_marginEnd="8dp"
        android:src="@drawable/ic_search" />

</FrameLayout>

進階:可點擊、狀態切換

  • 將 ImageView 換為 ImageButton 或設定 android:clickable="true" + setOnClickListener。
  • 用 TextView.setCompoundDrawablesRelativeWithIntrinsicBounds 動態設定右側圖標(API 17+)。

Material Components 現成元件


<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:endIconMode="clear_text"> <!-- 或 password_toggle, custom -->

    <com.google.android.material.textfield.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</com.google.android.material.textfield.TextInputLayout>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved