<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="搜索..."
android:drawableRight="@drawable/ic_search"
android:drawablePadding="8dp" />
圖片作為 EditText 复合繪製對象,**無法直接監聽點擊**。
<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>
ImageButton btnSearch = findViewById(R.id.btn_search);
btnSearch.setOnClickListener(v -> {
String query = editText.getText().toString();
performSearch(query);
});
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);
}
// ...
});