基本食譜
這項做法會顯示基本範例,說明如何搭配兩個畫面使用 Navigation 3 API。
運作方式
這個範例定義了兩條路徑:RouteA 和 RouteB。RouteA 是代表簡單畫面的 data object,而 RouteB 則是將 id 做為參數的 data class。
mutableStateListOf<Any> 用於管理導覽返回堆疊。
NavDisplay 可組合函式用於顯示目前畫面。其 entryProvider 參數是 lambda,會從返回堆疊取得路徑並傳回 NavEntry。在 entryProvider 內,系統會使用 when 陳述式,根據路徑判斷要顯示哪個可組合函式。
如要從 RouteA 導覽至 RouteB,只要將 RouteB 執行個體新增至返回堆疊即可。id 會以引數的形式傳遞至 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.basic 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.compose.runtime.mutableStateListOf import androidx.compose.runtime.remember import androidx.lifecycle.compose.dropUnlessResumed import androidx.navigation3.runtime.NavEntry import androidx.navigation3.ui.NavDisplay import com.example.nav3recipes.content.ContentBlue import com.example.nav3recipes.content.ContentGreen import com.example.nav3recipes.ui.setEdgeToEdgeConfig private data object RouteA private data class RouteB(val id: String) class BasicActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { setEdgeToEdgeConfig() super.onCreate(savedInstanceState) setContent { val backStack = remember { mutableStateListOf<Any>(RouteA) } NavDisplay( backStack = backStack, onBack = { backStack.removeLastOrNull() }, entryProvider = { key -> when (key) { is RouteA -> NavEntry(key) { ContentGreen("Welcome to Nav3") { Button(onClick = dropUnlessResumed { backStack.add(RouteB("123")) }) { Text("Click to navigate") } } } is RouteB -> NavEntry(key) { ContentBlue("Route id: ${key.id} ") } else -> { error("Unknown route: $key") } } } ) } } }