Search code examples
androidandroid-edittextsearchbar

Prevent EditText in SearchBar from covering MenuItem Button


I cannot figure out how to get the EditText to not cover the area where my MenuItem icon button is within this SearchBar.

Is there no best way this is handled?

Layout snippet:

    <com.google.android.material.search.SearchBar
        android:id="@+id/app_config_search_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/app_config_toolbar"
        android:hint="@string/search_hint"
        app:menu="@menu/menu_searchbar">

        <EditText
            android:id="@+id/app_config_edit_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="text"/>
    </com.google.android.material.search.SearchBar>

search bar image

The 'X' clear icon button (MenuItem) is not clickable as the EditText is fully covering the whole width of the SearchBar.

I have tried changing layout_width to wrap_content, and a specific value e.g. 10dp, but nothing is able to change it.

I tried de-nesting EditText out of the SearchBar and I can then click on the button, but then I can't type into anything since EditText is no longer within the SearchBar.


Solution

  • I used a ConstraintLayout within the SearchBar to control the proportion of the EditText which prevents it from covering the SearchBar Menu.

        <com.google.android.material.search.SearchBar
        android:id="@+id/app_config_search_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/app_config_toolbar"
        android:hint="@string/search_hint"
        app:menu="@menu/menu_searchbar">
    
        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
    
            <EditText
                android:id="@+id/app_config_edit_text"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                app:layout_constraintWidth_percent="0.8"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                android:inputType="text" />
        </androidx.constraintlayout.widget.ConstraintLayout>
    </com.google.android.material.search.SearchBar>