jetpack compose 在两个页面间切换:
-
创建两个Compose页面:定义两个简单的Composable函数,分别代表两个页面。
kotlinimport androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.navigation.NavController @Composable fun FirstPage(navController: NavController) { Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text("这是第一页") Button(onClick = { navController.navigate("second_page") }) { Text("去第二页") } } } @Composable fun SecondPage(navController: NavController) { Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text("这是第二页") Button(onClick = { navController.popBackStack() }) { Text("返回第一页") } } }
-
设置导航图 :使用
NavHost
和NavController
来管理页面切换。kotlinimport androidx.compose.runtime.Composable import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.treevalue.jetsnack.pages.FirstPage import com.treevalue.jetsnack.pages.SecondPage @Composable fun AppNavigation() { val navController = rememberNavController() NavHost(navController = navController, startDestination = "first_page") { composable("first_page") { FirstPage(navController) } composable("second_page") { SecondPage(navController) } } }
-
在主活动中使用 :主活动中调用
AppNavigation
。kotlinclass MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AppNavigation() } } }