Chapter 27 Search
Responding to SearchView user interactions
When the user submits a query, your app should execute a search against the Flickr web
service and refresh the images the user sees with the search results. Fortunately, the
SearchView.OnQueryTextListener interface provides a way to receive a callback when a query is
submitted.
Update onCreateOptionsMenu(...) to add a SearchView.OnQueryTextListener to your SearchView.
Listing 27.9 Logging SearchView.OnQueryTextListener events
(PhotoGalleryFragment.java)
public class PhotoGalleryFragment extends Fragment {
...
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
super.onCreateOptionsMenu(menu, menuInflater);
menuInflater.inflate(R.menu.fragment_photo_gallery, menu);
MenuItem searchItem = menu.findItem(R.id.menu_item_search);
final SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
Log.d(TAG, "QueryTextSubmit: " + s);
updateItems();
return true;
}
@Override
public boolean onQueryTextChange(String s) {
Log.d(TAG, "QueryTextChange: " + s);
return false;
}
});
}
private void updateItems() {
new FetchItemsTask().execute();
}
...
}
In onCreateOptionsMenu(...), you pull the MenuItem representing the search box from the menu
and store it in searchItem. Then you pull the SearchView object from searchItem using the
getActionView() method.
Once you have a reference to the SearchView, you are able to set a SearchView.OnQueryTextListener
using the setOnQueryTextListener(...) method. You must override two methods in the
SearchView.OnQueryTextListener implementation: onQueryTextSubmit(String) and
onQueryTextChange(String).
The onQueryTextChange(String) callback is executed any time text in the SearchView text box
changes. This means that it is called every time a single character changes. You will not do anything
inside this callback for this app except log the input string.