For a little bit of polish, pre-populate the search text box with the saved query when the user presses the search icon to expand the search view.
First, add a computed property to PhotoGalleryViewModel to expose the search term the UI is currently displaying results for.
Listing 26.15 Exposing the search term from PhotoGalleryViewModel
(PhotoGalleryViewModel.java
)
class PhotoGalleryViewModel(private val app: Application) : AndroidViewModel(app) { ... private val mutableSearchTerm = MutableLiveData<String>() val searchTerm: String get() = mutableSearchTerm.value ?: "" init { ... } ... }
SearchView’s View.OnClickListener.onClick() function is called when the user presses the search icon. Hook into this callback and set the SearchView’s query text when the view is expanded.
Listing 26.16 Pre-populating SearchView
(PhotoGalleryFragment.java
)
class PhotoGalleryFragment : Fragment() { ... override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { ... searchView.apply { setOnQueryTextListener(object : SearchView.OnQueryTextListener { ... }) setOnSearchClickListener { searchView.setQuery(photoGalleryViewModel.searchTerm, false) } } } ... }
Run your app and play around with submitting a few searches. Revel at the polish your last bit of code added. Of course, there is always more polish you could add…
3.145.64.241