0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

NavigationでSafe Argsを使って値を渡す方法(Kotlin)

Last updated at Posted at 2023-07-01

はじめに

Navigationを使っている場合、「Safe Args」という機能を使うことで、フラグメント間で値を型安全に渡せます。

Safe ArgsはNavigationとは別に設定する必要があり、セットアップや使い方を紹介します。

BundleやViewModelとの使い分け

基本的には「軽量のデータを渡すとき」にSafe Argsを使うのが望ましいです。
公式ドキュメントの内容を転記します。

一般に、デスティネーション間で渡すデータの量は、最小限に抑えることを強くおすすめします。たとえば、オブジェクト自体を渡すのではなく、オブジェクトを取得するためのキーを渡すようにします。これは、Android では、保存するすべての状態の合計容量が限られているためです。大量のデータを渡す必要がある場合は、 ViewModel を使用することをおすすめします。

引用: デスティネーション間でデータを渡す  |  Android デベロッパー  |  Android Developers

公式ドキュメントの内容をまとめると、以下のように使い分けるのがよさそうです。

  • 大量のデータを渡す必要がある → ViewModelを使う
  • Gradleを使っていないなど、Safe Argsが使えない → Bundleを使う
  • それ以外 → Safe Argsを使う

環境

  • OS:macOS Mojave 10.14.6
  • Kotlin:1.3.61
  • Gradle:5.6.4
  • Gradle plugin:3.6.2

セットアップ

前提条件として、Navigationがセットアップされているものとします。

インストール

appフォルダ配下の「build.gradle」にSafe Argsのプラグインを追加します。
モジュールにJavaが含まれている場合、代わりに "androidx.navigation.safeargs" を追加してください。

/app/build.gradle
+ apply plugin: 'androidx.navigation.safeargs.kotlin'

ルート直下の「build.gradle」にSafe Argsのクラスパスを追加します。
バージョンはNavigationと揃えます。

/build.gradle
buildscript {
    ext {
        nav_version = "2.3.0-alpha05"
    }

    dependencies {
+         classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
    }
}

使い方

TBD

おわりに

TBD

参考リンク

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?