[Jetpack Compose] Navigation遷移の基本

実装

dependencies

build.gradle.ktsに以下を追加、syncする。

implementation(libs.androidx.navigation.compose)

Navigation管理ファイル系

NavigationsScreens

ナビゲーション画面の種類を定義する場所

enum class NavigationScreens {
    HomeScreen,
    NextScreen;
    companion object {
        fun fromRoute(route: String?): NavigationScreens = when (route?.substringBefore("/")) {
            HomeScreen.name -> HomeScreen
            NextScreen.name -> NextScreen
            null -> HomeScreen
            else -> throw IllegalArgumentException("Route $route is not recognized.")
        }
    }
}

MockNavigation

@Composable
fun MockNavigation() {
    val navController = rememberNavController()
    NavHost(
        navController = navController,
        startDestination = NavigationScreens.HomeScreen.name // アプリ起動時の開始画面を指定
    ) {
        composable(NavigationScreens.HomeScreen.name) { 
            HomeScreen(navController = navController)
        }
        composable(NavigationScreens.NextScreen.name) {
            NextScreen(navController = navController)
        }
    }
}

メインの表示

MainActivity.kt

class MainActivity : ComponentActivity() {
    @OptIn(ExperimentalMaterial3Api::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyNavigation {
                MockNavigation() // HomeScreenを初期表示する
            }
        }
    }
}

@Composable
private fun MyNavigation(
    content: @Composable () -> Unit
) {
    MyPlaygroundTheme {
        content()
    }
}

HomeScreen.kt

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeScreen(
    navController: NavController
) {
    Scaffold(
        topBar = {
            TopAppBar(
                colors = TopAppBarDefaults.smallTopAppBarColors(containerColor = Color.Magenta),
                title = {
                    Text(text = "Navigation遷移")
                }
            )
        }
    ) { paddingValues ->
        Box(modifier = Modifier.padding(paddingValues)){
            Surface(
                modifier = Modifier
                    .fillMaxWidth()
                    .fillMaxHeight()
            ) {
                Column(
                    modifier = Modifier.padding(12.dp),
                    verticalArrangement = Arrangement.Center,
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(text = "Navigation遷移するよ")
                    Spacer(modifier = Modifier.height(12.dp))
                    Button(
                        modifier = Modifier
                            .width(240.dp)
                            .height(48.dp),
                        onClick = {
                            navController.navigate(route = NavigationScreens.NextScreen.name)
                        }
                    ) {
                        Text("Go to Next View")
                    }

                }
            }
        }
    }
}

NextScreen.kt

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NextScreen(navController: NavController) {
    Scaffold(
        topBar = {
            TopAppBar(
                colors = TopAppBarDefaults.smallTopAppBarColors(containerColor = Color.Magenta),
                title = {
                    Text(text = "Next Screen")
                },
                navigationIcon = {
                    IconButton(
                        onClick = {
                            navController.popBackStack()
                        }
                    ) {
                        Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "Arrow Back")
                    }
                }
            )
        }
    ) { _ ->
        Surface(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight()
        ) {
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                Text(text = "This is Next Screen")
            }
        }
    }
}