onClickListener for android material 3 search bar menu item

71 views Asked by At

In my activity i have a material 3 SearchBar and added a menu item inside searchBar but unable to have onClickListener

<com.google.android.material.appbar.AppBarLayout

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

    <com.google.android.material.search.SearchBar
        android:id="@+id/search_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="searchbar_hint"
        app:menu="@menu/search_bar_menu_inside_action_bar"/>

</com.google.android.material.appbar.AppBarLayout>

i tried to have onClickListener inside onCreateOptionsMenu and onOptionsItemSelected calling but nothing works

int itemId = item.getItemId();
    if (itemId == R.id.user_account) {
        // Do something when this menu item is clicked
        Toast.makeText(this, "success", Toast.LENGTH_SHORT).show();
        return true;
    }

Am not sure what am doing wrong. kindly help to over come this.

1

There are 1 answers

0
Name On

You can try it this way. I added an id for the appBarLayout and menu items. You can change them as you want.

   val appBarLayout = findViewById<AppBarLayout>(R.id.app_bar_layout)
   val searchBar = appBarLayout.findViewById<SearchBar>(R.id.search_bar)

    searchBar.setOnMenuItemClickListener { item ->
        when (item.itemId) {
            R.id.action1 -> {
                Toast.makeText(this@MainActivity, "action 1", Toast.LENGTH_SHORT).show()
                true
            }

            R.id.action2 -> {
                Toast.makeText(this@MainActivity, "action 2", Toast.LENGTH_SHORT).show()
                true
            }

            else -> false
        }
    }