As an example I will use the project Viktor-Events. Please note that it is not production ready, so you will not find it on Google Play, but you can clone the repository, compile it and run it from Android Studio.
Adding Navigation
To use Navigation (Architecture component), use the following dependencies:
Unfortunately, the libraries are still in alpha, but I’ve been able to use it in this project, as well as in the production-ready Wiktor-Navigator.
The navigation graph, though too big to embed in this article, can be vieved in XML form directly on GitHub.
The code that actually embeds the Fragments, using Navigation Architecture component, into their Activity is as follows.
Implementing the Activity and Fragment
The Activity and Fragment share one instance of ViewModel:
An instance of it is acquired in the Activity this way:
And in the Fragment this way, together with observing the value of query:
Please note the shared instance of ViewModel needs to be retrieved specifically in the function onViewCreated(), and not in onCreateView().
Setting the value of query is performed in the Activity’s function onNewIntent():
Because both Activity and the Fragment share the same instance of the ViewModel, the Fragment may listen to the value changes of the LiveData that is set in the Activity.
Configuring the Activity in AndroidManifest.xml
This is the way the Activity is configured in AndroidManifest.xml so that it handles android.intent.action.SEARCHIntents, and that only one instance of it may be run (the parameter singleTop):
This is the content of the XML file configuring searchable content in the Activity:
Adding the Search option menu in the Fragment
This is the code that adds Search option menu to the Fragment:
This is, finally, the XML file that adds the search edit box to the GUI as an option menu: