Search code examples
androidmaterial-designonclicklistenerandroid-toolbarandroid-appbarlayout

MaterialToolBar ontouch never called


I've got a simple set up:

<?xml version="1.0" encoding="utf-8"?>
 <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:id="@+id/ddd"
 android:layout_height="match_parent"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 tools:context=".pkgTestforend.DriverListFragment">



    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:liftOnScroll="true" >

            <com.google.android.material.appbar.MaterialToolbar
                android:id="@+id/topAppBar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:title="PageTitle"
                app:menu="@menu/top_app_bar"
                app:layout_scrollFlags="scroll|enterAlways"
                app:navigationIcon="@drawable/baseline_menu_24"
                style="@style/Widget.MaterialComponents.Toolbar.Primary"
                />

    </com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

And:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/search"
        android:icon="@drawable/baseline_search_24"
        android:title="Search"
        android:contentDescription="contdescript"
        app:actionViewClass="androidx.appcompat.widget.SearchView"
        app:showAsAction="ifRoom" />

    <item
        android:id="@+id/favorite"
        android:icon="@drawable/baseline_favorite_24"
        android:title="Favorite"
        android:contentDescription="Contentdescription"
        app:showAsAction="ifRoom" />



    <item
        android:id="@+id/more"
        android:title="more"
        android:icon="@drawable/baseline_more_vert_24"
        android:contentDescription="kljlkj"
        app:showAsAction="never" />

</menu>

Setting up toolbar: https://snippi.com/s/xyogasj

The issue is that altough i followed each step defined here, the ontouch menuitem listener never gets called, regardless wether I am using the listener or the override method, what am I missing?


Solution

  • Few things u should change:

    app:showAsAction="always|collapseActionView"
    

    this guarantess that searchview is always shown, otherwise u wont receive the ontouchlistener. For more information look here

    Second thing: Make sure your MaterialToolBar is clickable:

    android:clickable="true"