Search code examples
androidsearchview

Read search query in current fragment without launching activity


I am building an app which contains a signle Activity which contains an ActionBar. The activity contains a tab host with 4 tabs and each can be searched for something else, depending on the tab and fragment that is displayed.

According to the developer guide (https://developer.android.com/training/search/setup.html#add-sv), when pressing the search button after the user has entered his query, the activity will be launched with a search intent in which I can read the query like this:

if (Intent.ACTION_SEARCH.equals(intent.getAction())) 
{
        String query = intent.getStringExtra(SearchManager.QUERY);
        //use the query to search your data somehow
}

However, I don't want to relaunch the activity, then decide which fragment raised the query, set the tabs to the correct one, constructing a new fragment and so on... What I want to do is simply read the query itself inside the fragment which the user type in (I noticed that the SearchView class got a getQuery method).

How can I somehow implement a listener that reads the query after the user has finished writing his query and pressed the search button in the virtual keyboard without recreating the activity? I want to just get a reference to the search box and use it like it's a TextView, read it's text and use it.


Solution

  • What I eventually did was implementing OnQueryTextListener. This listener got 2 methods: onQueryTextChange which is called on every key pressed with the text as the parameter, and onQueryTextSubmit which is invoked when the user presses the search button. If you return true in onQueryTextSubmit, it means that everything is handled and there is no need to launch an intent.