Search code examples
androidmobilemenutoolbarsearchview

How to add QueryTextListener for searchView in android fragment?


I have an in app contacts list screen (which is a fragment) and I want to add a searchView in my toolbar. This is my code:

Fragment code:

    private lateinit var contactsToolbar: Toolbar

      override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
        val rootView = inflater.inflate(R.layout.fragment_contacts, container, false)
        setHasOptionsMenu(true);
        contactsToolbar = rootView.findViewById(R.id.contacts_toolbar)
        contactsToolbar.inflateMenu(R.menu.contacts_menu)
        contactsToolbar.title = "Contacts"
.......
      return rootView
    }

override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.contacts_menu, menu)
val search = menu.findItem(R.id.action_search)
val searchView = search.actionView as SearchView

searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
    override fun onQueryTextSubmit(query: String?): Boolean {
        Log.d(TAG, "new query $query")
        return true
    }

    override fun onQueryTextChange(newText: String?): Boolean {
        Log.d(TAG, "new text $newText")
        return true
    }
})
super.onCreateOptionsMenu(menu, inflater)

}

and this is my menu

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_search"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="always|collapseActionView"
        app:actionViewClass="androidx.appcompat.widget.SearchView"
        android:title="Search"/>
</menu>

I can see that the searchView is displayed in the fragmanet as expected but the queryTextListener never gets called. Does anyone have any idea why this is happening? Thank you in advance!


Solution

  • Found a solution! Not sure if is the most elegant one but might help somebody in the future. Here is the fix:

    1. In the onCreateView add this line of code:

    yourActivity().setSupportActionBar(contactsToolbar)

    1. This will make the searchView listener work but it might display the menu from the activity if you have one. To prevent this from happening and this line in onCreateOptionsMenu before inflating your menu.

      menu.clear()