기록

[Android] 프레그먼트간 전환을 돕는 NavDirection 클래스 본문

[Study]/Android

[Android] 프레그먼트간 전환을 돕는 NavDirection 클래스

Dannnnnn 2022. 6. 2. 02:16
반응형

사용자가 Android Trivia 앱 내에서 게임 결과를 공유하려면 먼저 코드가 한 조각에서 다른 조각으로 매개 변수를 전달해야 합니다.

이러한 트랜잭션의 버그를 방지하고 유형 안전을 위해 SafeArgs라는 Gradle 플러그인을 사용합니다.

플러그인이 NavDirection 클래스를 생성하고 이러한 클래스를 코드에 추가합니다.

 

In later tasks in this codelab, you use the generated NavDirection classes to pass arguments between fragments.

 

SafeArgs 플러그인이 필요한 이유
종종 앱은 조각들 사이에 데이터를 전달해야 합니다. 한 Fragment에서 다른 Fragment로 데이터를 전달하는 한 가지 방법은 번들 클래스의 인스턴스를 사용하는 것입니다. Android 번들은 핵심 가치 저장소입니다.

 

Your app could use a Bundle to pass data from Fragment A to Fragment B. For example, Fragment A creates a bundle and saves the information as key-value pairs, then passes the Bundle to Fragment B. Then Fragment B uses a key to fetch a key-value pair from the Bundle. This technique works, but it can result in code that compiles, but then has the potential to cause errors when the app runs.

The kinds of errors that can occur are:

  • Type mismatch errors. For example, if Fragment A sends a string but Fragment B requests an integer from the bundle, the request returns the default value of zero. Since zero is a valid value, this kind of type mismatch problem does not throw an error when the app is compiled. However, when the user runs the app, the error might make the app misbehave or crash.
  • Missing key errors. If Fragment B requests an argument that isn't set in the bundle, the operation returns null. Again, this doesn't throw an error when the app is compiled but could cause severe problems when the user runs the app.

You want to catch these errors when you compile the app in Android Studio, so that you catch these errors before deploying the app into production. In other words, you want to catch the errors during app development so that your users don't encounter them.

To help with these problems, Android's Navigation Architecture Component includes a feature called Safe Args. Safe Args is a Gradle plugin that generates code and classes that help detect errors at compile-time that might not otherwise be surfaced until the app runs.



Set up and use the Safe Args plugin

Step 1: Add Safe Args to the project

  1. In Android Studio, open the project-level build.gradle file.
  2. Add the navigation-safe-args-gradle-plugin dependency, as shown below:
 
// Adding the safe-args dependency to the project Gradle file
dependencies {
   ...
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$navigationVersion"

}
  1. Open the app-level build.gradle file.
  2. At the top of the file, after all the other plugins, add the apply plugin statement with the androidx.navigation.safeargs plugin:
 
// Adding the apply plugin statement for safeargs
apply plugin: 'androidx.navigation.safeargs'
  1. Re-build the project. If you are prompted to install additional build tools, install them.

The app project now includes generated NavDirection classes.

The Safe Args plugin generates a NavDirection class for each Fragment. These classes represent navigation from all the app's actions.

For example, GameFragment now has a generated GameFragmentDirections class. You use the GameFragmentDirections class to pass type-safe arguments between the game Fragment and other fragments in the app.

To see the generated files, explore the generatedJava folder in the Project > Android pane.

Caution: Do not edit the NavDirection classes. These classes are regenerated whenever the project is compiled, and your edits will be lost.

Step 2: Add a NavDirection class to the game Fragment

In this step, you add the GameFragmentDirections class to the game Fragment. You'll use this code later to pass arguments between the GameFragment and the game-state fragments (GameWonFragment and GameOverFragment).

  1. Open the GameFragment.kt Kotlin file that's in the java folder.
  2. Inside the onCreateView() method, locate the game-won conditional statement ("We've won!"). Change the parameter that's passed into the NavController.navigate() method: Replace the action ID for the game-won state with an ID that uses the actionGameFragmentToGameWonFragment() method from the GameFragmentDirections class.

The conditional statement now looks like the following code. You'll add parameters to the actionGameFragmentToGameWonFragment() method in the next task.

 
// Using directions to navigate to the GameWonFragment
view.findNavController()
        .navigate(GameFragmentDirections.actionGameFragmentToGameWonFragment())
  1. Likewise, locate the game-over conditional statement ("Game over!"). Replace the action ID for the game-over state with an ID that uses the game-over method from the GameFragmentDirections class:
 
// Using directions to navigate to the GameOverFragment
view.findNavController()
        .navigate(GameFragmentDirections.actionGameFragmentToGameOverFragment())
반응형