3.2 Define navigation paths

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 is false (default), popUpTo removes destinations up to the specified destination, but leaves the specified destination in the back stack.
  • If popUpToInclusive is set to true, the popUpTo attribute removes all destinations up to and including the given destination from the back stack.
  • If popUpToInclusive is true and popUpTo 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:

  1. Open the MainActivity.kt. Inside the onCreate() method, add code to find the navigation controller object:
    val navController = this.findNavController(R.id.myNavHostFragment)
    
  2. Also inside the onCreate() method, add code to link the navigation controller to the app bar:
    NavigationUI.setupActionBarWithNavController(this,navController)
    
  3. After the onCreate() method, override the onSupportNavigateUp() method to call navigateUp() in the navigation controller:
    override fun onSupportNavigateUp(): Boolean {
        val navController = this.findNavController(R.id.myNavHostFragment)
        return navController.navigateUp()
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值