ui: fix backstack behavior

Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
This commit is contained in:
Harsh Shandilya 2020-12-01 22:06:13 +05:30
parent 2b2acd1311
commit 39d36eece6
No known key found for this signature in database
GPG key ID: 366D7BBAD1031E80
2 changed files with 16 additions and 11 deletions

View file

@ -54,17 +54,16 @@ class MainActivity : AppCompatActivity() {
fun LobstersApp() {
val viewModel: LobstersViewModel = viewModel()
val navController = rememberNavController()
val destinations = arrayOf(Destination.Hottest, Destination.Saved)
val hottestPosts by viewModel.posts.collectAsState()
val savedPosts by viewModel.savedPosts.collectAsState()
Scaffold(
bottomBar = {
LobstersBottomNav(navController, destinations)
LobstersBottomNav(navController)
},
) { innerPadding ->
val hottestPostsListState = rememberLazyListState()
NavHost(navController, startDestination = Destination.Hottest.route) {
NavHost(navController, startDestination = Destination.startDestination.route) {
composable(Destination.Hottest.route) {
HottestPosts(
posts = hottestPosts,
@ -88,20 +87,21 @@ fun LobstersApp() {
@Composable
fun LobstersBottomNav(
navController: NavHostController,
destinations: Array<Destination>,
) {
BottomNavigation {
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.arguments?.getString(KEY_ROUTE)
destinations.forEach { screen ->
val currentRoute =
navBackStackEntry?.arguments?.getString(KEY_ROUTE) ?: Destination.startDestination.route
Destination.values().forEach { screen ->
BottomNavigationItem(
icon = { IconResource(resourceId = screen.badgeRes) },
label = { Text(stringResource(id = screen.labelRes)) },
selected = currentRoute == screen.route,
alwaysShowLabels = false,
onClick = {
if (currentRoute != screen.route) {
navController.popBackStack(navController.graph.startDestination, false)
if (currentRoute == screen.route) return@BottomNavigationItem
navController.popBackStack(navController.graph.startDestination, false)
if (screen.route != Destination.startDestination.route) {
navController.navigate(screen.route)
}
}

View file

@ -7,11 +7,16 @@ import dev.msfjarvis.lobsters.R
/**
* Destinations for navigation within the app.
*/
sealed class Destination(
enum class Destination(
val route: String,
@StringRes val labelRes: Int,
@DrawableRes val badgeRes: Int,
) {
object Hottest : Destination("hottest", R.string.hottest_posts, R.drawable.ic_whatshot_24px)
object Saved : Destination("saved", R.string.saved_posts, R.drawable.ic_favorite_24px)
Hottest("hottest", R.string.hottest_posts, R.drawable.ic_whatshot_24px),
Saved("saved", R.string.saved_posts, R.drawable.ic_favorite_24px),
;
companion object {
val startDestination = Hottest
}
}