AndroidでNavigationの画面遷移をやって分からないことをまとめた
の続編
前回のサンプルを使ったまま
SafeArgsを使ってみた
・セットアップ
1 2 | classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.2.1" apply plugin: "androidx.navigation.safeargs.kotlin" |
・XMLのセットアップ
UIからargumentを追加する
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | < fragment android:id = "@+id/secondFragment" android:name = "com.example.navigation.SecondFragment" android:label = "fragment_second" tools:layout = "@layout/fragment_second" > < action android:id = "@+id/action_second_to_third" app:destination = "@+id/thirdFragment" app:enterAnim = "@anim/slide_from_bottom" app:exitAnim = "@anim/slide_to_top" /> < argument android:name = "count" app:argType = "integer" android:defaultValue = "0" /> </ fragment > |
・FirstFragment
argumentを定義するとメソッドが追加されるパターンなのでcleanしてrebuildしましょう
遷移先じゃなくて遷移元にメソッドが生える
1 2 3 4 | view.button.setOnClickListener { val diretion = FirstFragmentDirections.actionFirstToSecond( 2 ) findNavController().navigate(diretion) } |
・SecondFragment
navArgsに移譲するとメソッドが生える
1 2 | val args: SecondFragmentArgs by navArgs() val count = args.count |
これにて実装終わり
型が定義されるしコード量少なくなるし良いことづくめ
ただ既存のbundle突っ込んでるところ書き換えるにはnavigation導入しないといけないのでちょっと難易度は高いなぁ・・・
ここまで勉強して新規プロジェクトだったら調べながらできるところまできた予感
・参考サイト
https://developer.android.com/guide/navigation/navigation-pass-data?hl=ja
https://ticktakclock.hatenablog.com/entry/2020/02/02/170615
関連記事:
- Androidで画像を指に沿って移動し離したら元の位置に戻す
- AndroidでLiveDataのTransformationsを使ってみた
- Android Studio 4.0のMotion Editorでアニメーションを作ってみた