我遇到的问题是,在屏幕之间转换时,顶部应用栏始终首先出现,并且不跟随预期屏幕的转换。
所示代码:
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
NotesTheme {
MainApp()
}
}
}
}
@Composable
fun MainApp(
appNavController: NavHostController = rememberNavController()
) {
val backStackEntry by appNavController.currentBackStackEntryAsState()
val currentScreen = backStackEntry?.destination?.route
Scaffold(
topBar = {
if (currentScreen == AppScreen.Add.route) {
TopBar(
navigateUp = {
appNavController.navigateUp()
},
isActionsActive = false,
isActionsClick = {}
)
}
},
) { innerPadding ->
AppNavHost(appNavController = appNavController, modifier = Modifier.padding(innerPadding))
}
}
// I've provided a longer transition duration to make the difference more noticeable
fun NavGraphBuilder.addGraph(
appNavController: NavHostController
) {
composable(
route = AppScreen.Add.route,
arguments = AppScreen.Add.navArguments,
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Start, tween(1000)
)
},
exitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.End, tween(1000)
)
},
content = {
AddScreen(appNavController = appNavController)
}
)
}
您可以在
AppNavHost
可组合项中应用动画。因此,动画将仅应用于您在 NavHost 中显示的可组合项,而不是应用于与 NavHost 处于同一级别的脚手架。
要将动画也应用到支架,您必须将支架的
topBar
从 MainApp
可组合项移动到 AddScreen
可组合项中的单独支架中:
@Composable
fun MainApp(
appNavController: NavHostController = rememberNavController()
) {
val backStackEntry by appNavController.currentBackStackEntryAsState()
val currentScreen = backStackEntry?.destination?.route
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) { innerPadding ->
AppNavHost(appNavController = appNavController, modifier = Modifier.padding(innerPadding))
}
}
然后更新您的
AddScreen
可组合项:
@Composable
fun AddScreen(appNavController : NavController) {
Scaffold(
topBar = {
TopBar(
navigateUp = {
appNavController.navigateUp()
},
isActionsActive = false,
isActionsClick = {}
)
}
) { innerPadding ->
// ...
// your content that you previously had in here
// don't forget to apply innerPadding to the topmost Composable in here
}
}