Conditional Navigation 조건에 맞춰 Navigation을 해보자.

앱에서 사용자가 "구입하기" 버튼을 눌렀을 때, 회원가입이 되어 있다면 구매페이지로, 되어있지 않다면 회원가입 페이지로 이동해야 한다면 어떻게 구현해야 할까요? 이번 포스팅에서는 안드로이드 Navigation Component를 이용해 조건별로 화면 이동하는 방법에 대해서 알아 보겠습니다.

 

이번 포스팅은 이전 포스팅과 이어집니다.

https://devlopsquare.tistory.com/11

 

안드로이드 Navigation Components로 Fragment들을 전환해 보자.

Android Jetpack의 Navigation Component는 안드로이드 앱을 제작 할 때 화면간의 이동을 조금 더 쉽게 구현 할 수 있도록 도와줍니다. Navigation Component는 세 가지 주요 부분으로 구성 됩니다. Navigation G..

devlopsquare.tistory.com

 

이전 포스팅에서는 사용자 Play 버튼을 눌렀을 때 GameFragment로 이동하는 것 까지 구현하였습니다. 사용자가 게임을 마친다면, 게임을 이긴 경우, 진 경우 이렇게 두가지 경우가 발생합니다. 각 상황에 맞춰 화면으로 Navigation 하는 방법을 알아 보겠습니다.

 

Step1. Add GameWonFragment and GameOverFragment to the Navigation graph


이전 시간에 생성했던 navation.xml 파일을 열어주세요. 이곳에 fragment_game_over과 fragment_game_own을 추가해 주세요.

 

이 때, game-over-fragment의 ID는 gameOverFragment 이고, game-won-fragment의 ID는 gameOwnFragment여야 합니다. 

 

 

 

 

Step2. Connect the game fragment to the game-result fragmet


GameWonFragment와 GameOverFragment를 추가 해 주셨다면, 이 두 프래그먼트와 GameFragment를 아래와 같이 서로 연결 시켜 줍니다. 연결 시키면 자동으로 action (연결된 선)의 ID가 action_gameFragment_to_gameWonFragment로 지정된 것을 확인하실 수 있습니다.

 

 

Step 3: Add code to navigation from one fragment to the next


GameFragment에는 사용자가 제출 한 답을 체크하여 게임에 이겼는지, 졌는지 결정하는 로직이 들어 있습니다. 이 로직은 sumitButton을 눌렀을 때 수행됩니다. 그러면 이겼는지, 졌는지 체크가 완료된 뒤에 GameFragment에서는 무엇을 해야 할까요? 상황에 맞춰 위에서 생성한 GameOverFragment 또는 GameWonFragment로 화면을 이동 시켜 주어야 합니다.

 

GameFragment의 onCreate() 안에 다음과 같이 submitButtion의 click listener가 정의되어 있습니다. 코드를 살펴 보면  anwers[answerIndex] 에는 사용자가 선택한 답이 들어갑니다. currentQuesttion.answers[0]에는 정해진 답이 들어 있습니다.

 

정답이라면 questionIndex를 증가시켜 주고 정해진 문제의 개수 (numQuestions) 보다 작으면 새 문제를 셋팅해 줍니다.

그러나 틀린 다면, GameOverPage로 이동시켜 주어야 합니다. 하나라도 틀리면 이곳으로 가야겠네요.

 

questionIndex가 numQuestions보다 같거나 커진다면, GaveWonPage로 이동해야 합니다.

 

binding.submitButton.setOnClickListener @Suppress("UNUSED_ANONYMOUS_PARAMETER")
        { 
              ...
                // 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.
                    }
                } else {
                    // Game over! A wrong answer sends us to the gameOverFragment.
                }
            }
        }

 

각 상황에는 어떤 코드들이 들어가야 해당 화면으로 이동하는지 알아 보겠습니다.

 

게임에 이겼을 경우에는 아래와 같은 코드를 넣어 주세요. action의 ID로 부터 직관적으로 GameFragment에서 GameWonFragment로 이동 하는 것이구나 하고 알 수 있습니다.

// We've won!  Navigate to the gameWonFragment.
view.findNavController()
   .navigate(R.id.action_gameFragment_to_gameWonFragment)

 

게임에 진 경우에는 아래와 같은 코드를 넣어주시면 됩니다.

 

// Game over! A wrong answer sends us to the gameOverFragment.
view.findNavController().
   navigate(R.id.action_gameFragment_to_gameOverFragment)

댓글



Designed by JB FACTORY