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

Android EditText 內嵌圖片按鈕:drawableRight 或 RelativeLayout 疊加實現

     編輯:程式設計綜合問答

方案一:drawableRight(無點擊響應,僅裝飾)

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="搜索..."
    android:drawableRight="@drawable/ic_search"
    android:drawablePadding="8dp" />

圖片作為 EditText 复合繪製對象,**無法直接監聽點擊**。

方案二:RelativeLayout 疊加 ImageButton(可點擊)

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

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="搜索..."
        android:paddingRight="50dp" /> <!-- 預留右側空間 -->

    <ImageButton
        android:id="@+id/btn_search"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_margin="5dp"
        android:src="@drawable/ic_search"
        android:background="?attr/selectableItemBackgroundBorderless" />

</RelativeLayout>

Activity 中監聽

ImageButton btnSearch = findViewById(R.id.btn_search);
btnSearch.setOnClickListener(v -> {
    String query = editText.getText().toString();
    performSearch(query);
});

進階:TextWatcher 動態顯示/隱藏按鈕

editText.addTextChangedListener(new TextWatcher() {
    @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
        btnSearch.setVisibility(s.length() > 0 ? View.VISIBLE : View.GONE);
    }
    // ...
});
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved