기본 DSL 레시피

이 레시피는 entryProvider DSL과 지속적인 뒤로 스택을 사용하여 화면이 두 개인 Navigation 3 API를 사용하는 기본 예를 보여줍니다.

작동 방식

이 예는 기본 레시피와 비슷하지만 몇 가지 중요한 차이점이 있습니다.

  1. 영구 뒤로 스택: rememberNavBackStack(RouteA)를 사용하여 뒤로 스택을 만들고 기억합니다. 이렇게 하면 구성 변경 (예: 화면 회전) 시 뒤로 스택이 지속됩니다. rememberNavBackStack를 사용하려면 탐색 키가 직렬화 가능해야 합니다. 따라서 RouteARouteB에는 @Serializable 주석이 달려 있고 NavKey 인터페이스가 구현되어 있습니다.

  2. entryProvider DSL: 이 예에서는 when 문 대신 entryProvider DSL을 사용하여 각 경로의 콘텐츠를 정의합니다. entry<RouteType> 함수는 경로 유형을 컴포저블 콘텐츠와 연결하는 데 사용됩니다.

탐색 로직은 동일하게 유지됩니다. RouteA에서 RouteB으로 이동하려면 RouteB 인스턴스를 뒤로 스택에 추가합니다.

/*
 * Copyright 2025 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.nav3recipes.basicdsl

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.navigation3.runtime.NavKey
import androidx.navigation3.runtime.entryProvider
import androidx.navigation3.runtime.rememberNavBackStack
import androidx.navigation3.ui.NavDisplay
import com.example.nav3recipes.content.ContentBlue
import com.example.nav3recipes.content.ContentGreen
import com.example.nav3recipes.ui.setEdgeToEdgeConfig
import kotlinx.serialization.Serializable

@Serializable
private data object RouteA : NavKey

@Serializable
private data class RouteB(val id: String) : NavKey

class BasicDslActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        setEdgeToEdgeConfig()
        super.onCreate(savedInstanceState)
        setContent {
            val backStack = rememberNavBackStack(RouteA)

            NavDisplay(
                backStack = backStack,
                onBack = { backStack.removeLastOrNull() },
                entryProvider = entryProvider {
                    entry<RouteA> {
                        ContentGreen("Welcome to Nav3") {
                            Button(onClick = {
                                backStack.add(RouteB("123"))
                            }) {
                                Text("Click to navigate")
                            }
                        }
                    }
                    entry<RouteB> { key ->
                        ContentBlue("Route id: ${key.id} ")
                    }
                }
            )
        }
    }
}