Notes: 05. Add Start Destination & NavHost Interface
Learn about Principles of Navigation and Creating Activity as Destination.
Open navigation graph in starter project. Click New Destination icon. You get a list which displays available activities and fragments in the app.
Add Main Fragment as Destination in the navigation graph. Switch to Code view and see the MainFragment added. Also, notice, MainFragment is the startDestination. Switch to Design view and this is indicated by Home icon to left of MainFragment
The Navigation component follows the guidance outlined in the Principles of Navigation. To learn more about Principles of Navigation and Creating Activity as Destination, refer to the link in the Description.
The Principles of Navigation recommend you use activities as entry points for your app. It manages any global navigation like Bottom Navigation, Navigation drawer etc. However,it doesn’t own any contents, it delegates to NavHost for content.
Now , you’ll modify MainActivity to host NavHostFragment. As you are adding Fragments as Destinations, NavHostFragment is your NavHost - It is your container that swaps different Destination fragments IN and OUT.
Open activity_main.xml and add the following code:
<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" />
Here, you are specifying, NavHostFragment as the container.
defaultNavHost as true connects the system back button to the NavHostFragment.
navGraph associates the NavHostFragment with a navigation graph specified. Now Build & Run the App
You can see that MainFragment is your Start Destination. Click on Login OR SignUp button.
Nothing happens. Don’t worry. You will hook that up in the next episode.