}
}
PageOne页面中有个按钮,点击按钮跳转到页面2,为了便于区分,添加一个Text用来显示当前页面内容。
接着来看PageTwo的代码,如下所示:
@Composable
fun PageTwo() {
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.background(
Color.White
)
) {
Text(text = “这是页面2”)
Spacer(modifier = Modifier.height(20.dp))
Button(onClick = {
//点击返回页面1
}) {
Text(
text = “返回页面1”,
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center
)
}
}
}
MainActivity代码如下所示:
setContent {
NavigationTheme {
// A surface container using the ‘background’ color from the theme
Surface(color = MaterialTheme.colors.background) {
PageOne()
}
}
}
运行程序,显示出页面1 ,如图所示。

接下来我们来看,如何使用navigation来进行页面导航呢?
定义NavHost
首先我们定义一个NavHost对象
@Composable
fun NavHostDemo() {
NavHost(navController =, startDestination =) {
}
}
NavHost对象需要两个必传参数,一个是NavController,一个是起始路由地址,NavController 对象是 Navigation 组件的中心 API,我们可以通过 rememberNavController创建,代码如下所示:
val navController = rememberNavController()
为了便于管理路由地址,我们新建RouteConfig配置文件,代码如下所示:
object RouteConfig {
/**
* 页面1路由
*/
const val ROUTE_PAGEONE = “pageOne”
/**
* 页面1路由
*/
const val ROUTE_PAGETWO = “pageTwo”
}
在这里,将页面1路由设置为起始导航,并使用composable方法添加导航对应关系,修改后的NavHostDemo代码如下所示:
@Composable
fun NavHostDemo() {
val navControlle

1207




被折叠的 条评论
为什么被折叠?



