トップ アプリバーから移動する

このガイドでは、トップ アプリバーのナビゲーション アイコンからナビゲーション アクションを実行する方法について説明します。

次のスニペットは、ナビゲーション アイコンが機能するトップ アプリバーを実装する簡単な例です。この場合、アイコンはユーザーをアプリ内の以前のデスティネーションに誘導します。

@Composable
fun TopBarNavigationExample(
    navigateBack: () -> Unit,
) {
    Scaffold(
        topBar = {
            CenterAlignedTopAppBar(
                title = {
                    Text(
                        "Navigation example",
                    )
                },
                navigationIcon = {
                    IconButton(onClick = navigateBack) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "Localized description"
                        )
                    }
                },
            )
        },
    ) { innerPadding ->
        Text(
            "Click the back button to pop from the back stack.",
            modifier = Modifier.padding(innerPadding),
        )
    }
}

コードに関する要点

この例では、次の点に注意してください。

  • コンポーザブル TopBarNavigationExample は、() -> Unit 型のパラメータ navigateBack を定義します。
  • CenterAlignedTopAppBarnavigationIcon パラメータに navigateBack を渡します。

そのため、ユーザーがトップアプリのナビゲーション アイコンをクリックするたびに navigateBack() が呼び出されます。

関数を渡す

この例では、アイコンに「戻る」矢印を使用しています。そのため、navigateBack() の引数は、ユーザーを前のデスティネーションに誘導する必要があります。

そのためには、TopBarNavigationExampleNavController.popBackStack() の呼び出しを渡します。これは、ナビゲーション グラフを作成する際に行います。次に例を示します。

NavHost(navController, startDestination = "home") {
    composable("topBarNavigationExample") {
        TopBarNavigationExample{ navController.popBackStack() }
    }
    // Other destinations...

参考情報

アプリにナビゲーションを実装する方法について詳しくは、次の一連のガイドをご覧ください。