1.添加依赖

implementation "androidx.navigation:navigation-compose:x.x.x"

2.设置navhostcontroller

var navController:NavHostController  = rememberNavController()

3.设置返回点

val backStackEntry by navController.currentBackStackEntryAsState()
val currentDestination =  backStackEntry?.destination

如果返回点错乱,则需要使用列表进行查找,比如:

var currentScreen  = rallyTabRowScreens.find { it.route == currentDestination?.route }?:Overview

4.NavHost设置

例如:

NavHost(
          navController = navController,
          startDestination = Overview.route,
          modifier = Modifier.padding(innerPadding)
        )
{
                composable(
                    route = Overview.route
                ) {
                    OverviewScreen()
                }

                composable(
                    route = Accounts.route
                ) {
                    AccountsScreen()
                }
}

5.路由名称的设置方法。

方法1:

interface RallyDestination {
    val icon: ImageVector
    val route: String
}

object Overview : RallyDestination {
    override val icon = Icons.Filled.PieChart
    override val route = "overview"
}
object Accounts : RallyDestination {
    override val icon = Icons.Filled.AttachMoney
    override val route = "accounts"

}
object Bills : RallyDestination {
    override val icon = Icons.Filled.MoneyOff
    override val route = "bills"

}

val rallyTabRowScreens = listOf(Overview, Accounts, Bills)

方法2:

enum class CupcakeScreen(@StringRes val title:Int){
    Start(title = R.string.app_name),
    Favor(title = R.string.flavor),
    Pickup(title = R.string.pickup_date),
    Summary(title = R.string.order_summary)
}

CupcakeScreen.Start.name

6.导航

指定界面:navController.navigate(_router)

返回上一次:navController.navigateUp()

7. 页面信息保存(单例与状态保存)

fun NavHostController.navigateSingleTopTo(
    route:String,
)= this.navigate(route){
    popUpTo(this@navigateSingleTopTo.graph.findStartDestination().id){
        saveState = true
    }
    launchSingleTop = true
    restoreState = true
}
Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐