5
4

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.

【Android】Navigationでよくある画面遷移時のクラッシュと対策

Last updated at Posted at 2023-03-31

Navigationによる遷移の問題

ボタンタップ時の遷移にnavController.navigate()を使用していると、時々こんなクラッシュが発生する

Fatal Exception: java.lang.IllegalArgumentException: Navigation action/destination a_to_b cannot be found from the current destination Destination

高速タップをした際などに既にdestinationでは遷移したことになっているのに遷移しようとしてクラッシュしている
(手元で再現したい人はnavController.navigate()を2回連続で呼んでみると簡単に再現する)

解決案

遷移前に今の画面を確認するような処理を入れることで解消する

if (navController.currentDestination?.id == 遷移元画面のID) {
    navController.navigate(遷移アクション)
}

毎回確認処理を入れるとコード量が無駄に増えていくので、以下のような拡張関数で処理をまとめる

fun NavController.isCurrentDestination(
    /** 対象の宛先 */
    @IdRes resId: Int
): Boolean {
    return currentDestination?.id == resId
}

あとは遷移時にはこの拡張関数を使うようにすれば解決する。

発展

今回は現在画面のチェックまでしか拡張関数化していないが、チェックから遷移までを拡張関数化すればよりコード量の削減と効率化に繋がりそう。

5
4
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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?