0
0

More than 1 year has passed since last update.

Android Jetpack Composeの画面遷移2(NavController+アニメーション)

Posted at

アニメーション付きのJetpack Composeの画面遷移

前回、NavControllerを使用して、Composable間の画面遷移を行いました。
今回は、これにアニメーションをつけようと思います。

環境

AndroidStudio:Flamingo | 2022.2.1 Patch 2
OS:macOS

Step1.ライブラリの追加

NavControllerを使用した画面遷移にアニメーションをつけようと、検索をすると
com.google.accompanist:accompanist-navigation-animation
というライブラリがヒットするかと思います。
しかしこのライブラリは、現時点(2023/7/1)でdeprecatedになっています。

上記ページのMigrationに従って、「androidx.navigation:navigation-compose」のバージョンを、「2.7.0-alpha01以上」にします。

build.gradle
    implementation platform('androidx.compose:compose-bom:2022.10.00')
    implementation 'androidx.compose.ui:ui'
    implementation 'androidx.compose.ui:ui-graphics'
    implementation 'androidx.compose.ui:ui-tooling-preview'
    implementation 'androidx.compose.material3:material3'
    implementation 'androidx.navigation:navigation-compose:2.7.0-beta01'

Step2.アニメーションを追加

ナビゲーションフラグにあるcomposable()に、アニメーションの定義を追加します。

MainActivity.kt
composable(
    route = Nav.TopScreen.name,
    enterTransition = { slideInHorizontally(initialOffsetX = { fullWidth -> fullWidth / 2 }, animationSpec = tween()) },
    exitTransition = { slideOutHorizontally(targetOffsetX = { fullWidth -> fullWidth / 2 }, animationSpec = tween()) },
    popEnterTransition = { slideInVertically(initialOffsetY = { fullHeight -> fullHeight / 2 }, animationSpec = tween()) },
    popExitTransition = { slideOutVertically(targetOffsetY = { fullHeight -> fullHeight / 2 }, animationSpec = tween()) },
) {

引数にある遷移タイミング(enterTransition, exitTransition, popEnterTransition, popExitTransition)に表現したいアニメーションを指定すればOKです。

いざ実行

ボタンを押して遷移すると、enterTransitionのアニメーションが実行されます。
また、デバイスの戻るボタンをタップして遷移元画面に戻るとpopExitTransitionが実行されます。コード
navcontroller_animation_AdobeExpress.gif

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