本文主要是介绍jetpack compose 在两个页面间切换,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
jetpack compose 在两个页面间切换:
-
创建两个Compose页面:定义两个简单的Composable函数,分别代表两个页面。
import 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
来管理页面切换。import 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
。class MainActivity : ComponentActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContent {AppNavigation()}} }
这篇关于jetpack compose 在两个页面间切换的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!