3.2 Define navigation paths
1. Introduction
What you’ll learn
- How to use navigation graphs
- How to define navigation paths in your app
- What an Up button is, and how to add one
- How to create an options menu
- How to create a navigation drawer
What you’ll do
- Create a navigation graph for your fragments using the navigation library and the Navigation Editor.
- Create navigation paths in your app.
- Add navigation using the options menu.
- Implement an Up button so that the user can navigate back to the title screen from anywhere in the app.
- Add a navigation drawer menu.
3. Task: Add navigation components to the project
Step 1: Add navigation dependencies
// in Project:build.gradle
ext {
...
navigationVersion = "2.3.0"
...
}
// in Module:build.gradle
dependencies {
...
implementation "androidx.navigation:navigation-fragment-ktx:$navigationVersion"
implementation "androidx.navigation:navigation-ui-ktx:$navigationVersion"
...
}
4. Task: Create the NavHostFragment
A navigation host fragment acts as a host for the fragments in a navigation graph. The navigation host Fragment is usually named NavHostFragment
.
As the user moves between destinations defined in the navigation graph, the navigation host Fragment swaps fragments in and out as necessary. The Fragment also creates and manages the appropriate Fragment back stack.
In layout file:
The navigation host Fragment needs to know which navigation graph resource to use. Add the app:navGraph
attribute and set it to the navigation graph resource, such as @navigation/navigation
.
Add the app:defaultNavHost
attribute and set it to “true
”. Now this navigation host is the default host and will intercept the system Back button.
5. Task: Add fragments to the navigation graph
Step 1: Add two fragments to the navigation graph and connect them with an action
注意要在
.xml
文件中加入tools:layout="@layout/..."
。
Step 2: Add a click handler to the Play button
class TitleFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val binding = DataBindingUtil.inflate<FragmentTitleBinding>(inflater, R.layout.fragment_title,container,false)
binding.playButton.setOnClickListener { view : View ->
view.findNavController()
.navigate(R.id.action_titleFragment_to_gameFragment)
}
setHasOptionsMenu(true)
return binding.root
}
}
6. Task: Add conditional navigation
In this step, you add conditional navigation, which is navigation that’s only available to the user in certain contexts. A common use case for conditional navigation is when an app has a different flow, depending on whether the user is logged in.
Your app is a different case: Your app will navigate to a different Fragment, based on whether the user answers all the questions correctly.
Step 1: Add GameWonFragment
and GameOverFragment
to the navigation graph
Step 2: Connect the game Fragment to the game-result Fragment
Step 3: Add code to navigate from one Fragment to the next
class GameFragment : Fragment() {
data class Question(
val text: String,
val answers: List<String>)
// The first answer is the correct one. We randomize the answers before showing the text.
// All questions must have four answers. We'd want these to contain references to string
// resources so we could internationalize. (Or better yet, don't define the questions in code...)
private val questions: MutableList<Question> = mutableListOf(
...
)
lateinit var currentQuestion: Question
lateinit var answers: MutableList<String>
private var questionIndex = 0
private val numQuestions = Math.min((questions.size + 1) / 2, 3)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
// Inflate the layout for this fragment
val binding = DataBindingUtil.inflate<FragmentGameBinding>(
inflater, R.layout.fragment_game, container, false)
// Shuffles the questions and sets the question index to the first question.
randomizeQuestions()
// Bind this fragment class to the layout
binding.game = this
// Set the onClickListener for the submitButton
binding.submitButton.setOnClickListener @Suppress("UNUSED_ANONYMOUS_PARAMETER")
{ view: View ->
val checkedId = binding.questionRadioGroup.checkedRadioButtonId
// Do nothing if nothing is checked (id == -1)
if (-1 != checkedId) {
var answerIndex = 0
when (checkedId) {
R.id.secondAnswerRadioButton -> answerIndex = 1
R.id.thirdAnswerRadioButton -> answerIndex = 2
R.id.fourthAnswerRadioButton -> answerIndex = 3
}
// The first answer in the original question is always the correct one, so if our
// answer matches, we have the correct answer.
if (answers[answerIndex] == currentQuestion.answers[0]) {
questionIndex++
// Advance to the next question
if (questionIndex < numQuestions) {
currentQuestion = questions[questionIndex]
setQuestion()
binding.invalidateAll()
} else {
// We've won! Navigate to the gameWonFragment.
view.findNavController()
.navigate(R.id.action_gameFragment_to_gameWonFragment)
}
} else {
// Game over! A wrong answer sends us to the gameOverFragment.
view.findNavController()
.navigate(R.id.action_gameFragment_to_gameOverFragment)
}
}
}
return binding.root
}
// randomize the questions and set the first question
private fun randomizeQuestions() {
questions.shuffle()
questionIndex = 0
setQuestion()
}
// Sets the question and randomizes the answers. This only changes the data, not the UI.
// Calling invalidateAll on the FragmentGameBinding updates the data.
private fun setQuestion() {
currentQuestion = questions[questionIndex]
// randomize the answers into a copy of the array
answers = currentQuestion.answers.toMutableList()
// and shuffle them
answers.shuffle()
(activity as AppCompatActivity).supportActionBar?.title = getString(R.string.title_android_trivia_question, questionIndex + 1, numQuestions)
}
}
7. Task: Change the Back button’s destination
The Android system keeps track of where users navigate on an Android-powered device. Each time the user goes to a new destination on the device, Android adds that destination to the back stack.
When the user presses the Back button, the app goes to the destination that’s at the top of the back stack. By default, the top of the back stack is the screen that the user last viewed.
In the AndroidTrivia app, when the user presses the Back button from the GameOverFragment or GameWonFragment screen, they end up back in the GameFragment. But you don’t want to send the user to the GameFragment, because the game is over. The user could restart the game, but a better experience would be to find themselves back at the title screen.
A navigation action can modify the back stack. In this task, you change the action that navigates from the game fragment so that the action removes the GameFragment
from the back stack. When the user wins or loses the game, if they press the Back button, the app skips the GameFragment
and goes back to the TitleFragment
.
Step 1: Set the pop behavior for the navigation actions
In this step, you manage the back stack so that when the user is at the GameWon or GameOver screen, pressing the Back button returns them to the title screen. You manage the back stack by setting the “pop” behavior for the actions that connect the fragments:
- The
popUpTo
attribute of an action “pops up” the back stack to a given destination before navigating. (Destinations are removed from the back stack.) - If the
popUpToInclusive
attribute isfalse
(default),popUpTo
removes destinations up to the specified destination, but leaves the specified destination in the back stack. - If
popUpToInclusive
is set to true, thepopUpTo
attribute removes all destinations up to and including the given destination from the back stack. - If
popUpToInclusive
istrue
andpopUpTo
is set to the app’s starting location, the action removes all app destinations from the back stack. The Back button takes the user all the way out of the app.
Step 2: Add more navigation actions and add onClick
handlers
In this step you implement two more steps of user flow:
- If the user taps the Next Match or Try Again button, the app navigates to the GameFragment screen.
- If the user presses the system Back button at this point, the app navigates to the TitleFragment screen (instead of back to the GameWon or GameOver screen).
8. Task: Add an Up button in the app bar
The app bar
The app bar
, sometimes called the action bar
, is a dedicated space for app branding and identity. For example, you can set the app bar’s color. The app bar gives the user access to familiar navigation features such as an options menu. To access the options menu from the app bar, the user taps the icon with the three vertical dots.
The app bar displays a title string that can change with each screen. For the title screen of the AndroidTrivia app, the app bar displays “Android Trivia.” On the question screen, the title string also shows which question the user is on (“1/3,” “2/3,” or “3/3.”)
The Up button
Currently in your app, the user uses the system Back button to navigate to previous screens. However, Android apps can also have an on-screen Up button that appears at the top left of the app bar.
In the AndroidTrivia app, you want the Up button to appear on every screen except the title screen. The Up button should disappear when the user reaches the title screen, because the title screen is at the top of the app’s screen hierarchy.
Up button versus Back button:
- The Up button appears in the app bar.
- The Up button navigates within the app, based on the hierarchical relationships between screens. The Up button never navigates the user out of the app.
- The Back button appears in the system navigation bar or as a mechanical button on the device itself, no matter what app is open.
- The Back button navigates backward through screens that the user has recently worked with (the back stack).
Add support for an Up button
The navigation components include a UI library called NavigationUI. The Navigation component includes a NavigationUI
class. This class contains static methods that manage navigation with the top app bar, the navigation drawer, and bottom navigation. The navigation controller integrates with the app bar to implement the behavior of the Up button, so you don’t have to do it yourself.
In the following steps, you use the navigation controller to add an Up button to your app:
- Open the
MainActivity.kt
. Inside theonCreate()
method, add code to find the navigation controller object:val navController = this.findNavController(R.id.myNavHostFragment)
- Also inside the
onCreate()
method, add code to link the navigation controller to the app bar:NavigationUI.setupActionBarWithNavController(this,navController)
- After the
onCreate()
method, override theonSupportNavigateUp()
method to callnavigateUp()
in the navigation controller:override fun onSupportNavigateUp(): Boolean { val navController = this.findNavController(R.id.myNavHostFragment) return navController.navigateUp() }