Jetpack Compose - Using Nested NavGraph with BottomNavBar and make Icons selected - android

I want to implement a BottomNavBar with 3 items.
Each navigating to a new navGraph. (Nested Navigation)
Home = "HomeGraph"
Explore = "ExploreGraph"
Profile = "ProfileGraph"
HomeGraph:
#OptIn(ExperimentalAnimationApi::class)
fun NavGraphBuilder.addHomeGraph(navController: NavHostController) {
navigation(
startDestination = "feed",
route = "HomeGraph"
) {
composable(
route = "feed"
) {
}
composable(
route = "comments"
) {
}
}
}
And my BottomNavBar navigates between those 3 graphs:
#Composable
fun BottomNavigationBar(navController: NavController) {
val items = listOf(
BottomNavigationItem.HomeGraph,
BottomNavigationItem.ExploreGraph,
BottomNavigationItem.ProfileGraph
)
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
BottomNavigation() {
Row(horizontalArrangement = Arrangement.Center) {
items.forEach { item ->
BottomNavigationItem(
icon = {
if (currentRoute == item.route) {
Icon(
painterResource(id = item.iconPressed),
contentDescription = item.title
)
} else {
Icon(
painterResource(id = item.iconNormal),
contentDescription = item.title
)
}
},
selectedContentColor = MaterialTheme.colors.primary,
unselectedContentColor = MaterialTheme.colors.onSurface,
alwaysShowLabel = false,
selected = currentRoute == item.route,
onClick = {
navController.navigate(item.route) {
navController.graph.startDestinationRoute?.let { route ->
popUpTo(route) {
saveState = true
}
}
launchSingleTop = true
restoreState = true
}
}
)
}
}
}
}
Now the problem is that my "Home" BottomNav Icon is not changing cause "selected" is never true.
selected = currentRoute == item.route,
How can I check if I am still on the same navigationGraph?
So when I go down the "HomeGraph" for example to "feed" or "comments" it should still indicate the "Home" Icon on my BottomNavBar as selected.
"feed" and "Comments" have in common, that their parent NavGraph is called "HomeGraph", how can I check for that?
With other words: I want pretty much the same BottomNavBar behaviour as Instagram

Instead of matching navBackStackEntry?.destination?.route, try looking for your route in the NavDestination's hierarchy.
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentDestination = navBackStackEntry?.destination
Then in your forEach:
val selected = currentDestination?.hierarchy?.any { it.route == item.route } == true

Related

Android BottomNavigation setting its background to some alfa, shows rectangle inside

When I try to set the backgroundColor to either from resource colors or by Color(0x44000000) inside the BottomNavigation bar strange rectangle is present. Could anyone explain why?
My code:
#Composable
fun Root() {
val navController = rememberNavController()
Scaffold(
bottomBar = {
BottomNavigation(backgroundColor = Color(0x44000000)) {
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
screens.forEach { screen ->
BottomNavigationItem(
icon = { Icon(screen.icon, contentDescription = null) },
label = { Text(text = screen.label) },
selected = currentRoute?.let{it == screen.route} ?: false,
onClick = {
navController.navigate(screen.route){
popUpTo(navController.graph.findStartDestination().id){
saveState = true
}
launchSingleTop = true
restoreState = true
}
})
}
}
}
) {
RootNavGraph(navController = navController)
}

How manage Navigation in Jetpack Compose application

I was developing an App with Jetpack Compose, and I try to implement the Navigation Compose component.
My use of case is based on 3 Screens without fragments:
List Screen
Detail Screen
Bought Screen
I also implement a BottomTab where I have List Screen and Bought Screen. the Detail Screen is access from List Screen.
BottomNavigation.kt
#Composable
fun BottomNavigationBar(heightBottomBar: Int, navController: NavController) {
Log.d("navigation", "navigatorName: ${navController.currentBackStackEntry?.destination?.navigatorName}")
Log.d("navigation", "displayName: ${navController.currentBackStackEntry?.destination?.displayName}")
Log.d("navigation", "arguments: ${navController.currentBackStackEntry?.arguments}")
val items = listOf(
BottomNavItem.ListScreen,
BottomNavItem.BoughtScreen
)
BottomNavigation(
Modifier.height(heightBottomBar.dp),
backgroundColor = MaterialTheme.colors.background,
contentColor = Color.White)
{
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
items.forEach { item ->
BottomNavigationItem(
icon = { Icon(painterResource(id = item.icon), contentDescription = item.title) },
label = {
Text(
text = item.title,
fontSize = 9.sp
)
},
selectedContentColor = androidx.compose.ui.graphics.Color.Black,
unselectedContentColor = androidx.compose.ui.graphics.Color.Black.copy(0.4f),
alwaysShowLabel = true,
selected = currentRoute == item.screen_route,
onClick = {
//Added to manage navigate to List screen, instead of detail screen when user pop List tab from BoughtScreen.
// if(item.screen_route == "pokemon_list_screen" && navBackStackEntry?.destination?.parent?.route == "pokemon_list_screen"){
// navController.popBackStack()
// }else{
navController.navigate(item.screen_route) {
navController.graph.startDestinationRoute?.let { screen_route ->
popUpTo(screen_route) {
saveState = true
}
}
launchSingleTop = true
restoreState = true
}
}
//}
)
}
}
}
And ButtonNav.kt file
sealed class BottomNavItem(var title:String, var icon:Int, var screen_route:String){
object BoughtScreen : BottomNavItem("My Pokemons", R.drawable.ic_all_inbox,"pokemon_bought_screen")
object ListScreen: BottomNavItem("List",R.drawable.ic_list,"pokemon_list_screen")
}
the issue is when I try to navigate from Bought Screen to List screen, pop in the List tab, which take me to detail screen, when it should take to List Screen.
The navigation implementation is the following:
#Composable
fun NavigationGraph(navController: NavHostController) {
NavHost(navController = navController, startDestination = Screens.List.route) {
composable(Screens.List.route) {
PokemonListScreen(navController = navController)
}
composable(
Screens.Detail.route,
// use as URL
//which pokemon you want to see in detail with colour in background pass arguments
arguments = listOf(
navArgument("dominantColor") {
type = NavType.IntType
},
navArgument("pokemonName") {
type = NavType.StringType
},
navArgument("number") {
type = NavType.IntType
}
),
) {
val dominantColor = remember {
val color = it.arguments?.getInt("dominantColor")
color?.let { Color(it) } ?: Color.White
}
val pokemonName = remember {
it.arguments?.getString("pokemonName")
}
val pokemonNumber = remember {
it.arguments?.getInt("number")
}
if (pokemonName != null) {
PokemonDetailScreen(
activity = this#MainActivity,
context = applicationContext,
dominantColor = dominantColor,
pokemonName = pokemonName.toLowerCase(Locale.ROOT) ?: " ",
pokemonNumber = pokemonNumber!!,
navController = navController
)
}
}
composable(Screens.Bought.route) {
MyPokemonsScreen(
context = applicationContext,
dominantColor = MaterialTheme.colors.background,
navController = navController
)
}
}
}
And my Screens.kt file:
sealed class Screens(val route: String) {
object List : Screens("pokemon_list_screen")
object Bought : Screens("pokemon_bought_screen")
object Detail : Screens("pokemon_detail_screen/{dominantColor}/{pokemonName}/{number}")
}
As I comment, with this implementation the apps works fine, except when I navigate to Bought Screen, and I click in the List Tab, the app take me to Detail Screen.
So my question is: Should I modify NavController to remove DetailScreen from currentBackStackEntry, or I should manage this from Bottomavigation::class.
I just start with Jetpack Compose, and I a bit undevelop on this topics.
If you have some knowledge about Jetpack Compose Navigation, and are able to help, take thanks in advance !

Jetpack compose navigation closes app instead of returning to previous screen

I have implemented the accompanist navigation animation library in my project and have stumbled into two issues. The first issue is that the animations aren't being applied when navigating from one screen to another. The second issue is that the "back" of the system closes the app to the background instead of returning to the previous screen.
Here is the layout of the app starting from the MainActivity.
MainActivity.kt
#ExperimentalAnimationApi
#AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private val preDrawListener = ViewTreeObserver.OnPreDrawListener { false }
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.MyHomeTheme)
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
val content: View = findViewById(android.R.id.content)
content.viewTreeObserver.addOnPreDrawListener(preDrawListener)
lifecycleScope.launch {
setContent {
val systemUiController = rememberSystemUiController()
SideEffect {
systemUiController.setStatusBarColor(
color = Color.Transparent,
darkIcons = true
)
systemUiController.setNavigationBarColor(
color = Color(0x40000000),
darkIcons = false
)
}
MyHomeApp(
currentRoute = Destinations.Welcome.WELCOME_ROUTE
)
}
unblockDrawing()
}
}
private fun unblockDrawing() {
val content: View = findViewById(android.R.id.content)
content.viewTreeObserver.removeOnPreDrawListener(preDrawListener)
content.viewTreeObserver.addOnPreDrawListener { true }
}
}
MyHomeApp.kt
#ExperimentalAnimationApi
#Composable
fun MyHomeApp(currentRoute: String) {
MyHomeTheme {
ProvideWindowInsets {
val navController = rememberAnimatedNavController()
val scaffoldState = rememberScaffoldState()
val darkTheme = isSystemInDarkTheme()
val items = listOf(
HomeTab.Dashboard,
HomeTab.Details,
HomeTab.Settings
)
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentDestination = navBackStackEntry?.destination
val bottomPaddingModifier = if (currentDestination?.route?.contains("welcome") == true) {
Modifier
} else {
Modifier.navigationBarsPadding()
}
Scaffold(
modifier = Modifier
.fillMaxSize()
.then(bottomPaddingModifier),
scaffoldState = scaffoldState,
bottomBar = {
if (currentDestination?.route in items.map { it.route }) {
BottomNavigation {
items.forEach { screen ->
BottomNavigationItem(
label = { Text(screen.title) },
icon = {},
selected = currentDestination?.hierarchy?.any { it.route == screen.route } == true,
onClick = {
navController.navigate(screen.route) {
// Pop up to the start destination of the graph to
// avoid building up a large stack of destinations
// on the back stack as users select items
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
// Avoid multiple copies of the same destination when
// reselecting the same item
launchSingleTop = true
// Restore state when reselecting a previously selected item
restoreState = true
}
}
)
}
}
}
}
) { innerPadding ->
MyHomeNavGraph(
modifier = Modifier.padding(innerPadding),
navController = navController,
startDestination = navBackStackEntry?.destination?.route ?: currentRoute
)
}
}
}
}
sealed class HomeTab(
val route: String,
val title: String
) {
object Dashboard : HomeTab(
route = Destinations.Home.HOME_DASHBOARD,
title = "Dashboard"
)
object Details : HomeTab(
route = Destinations.Home.HOME_DETAILS,
title = "Details"
)
object Settings : HomeTab(
route = Destinations.Home.HOME_SETTINGS,
title = "Settings"
)
}
MyHomeNavGraph.kt
#ExperimentalAnimationApi
#Composable
fun MyHomeNavGraph(
modifier: Modifier = Modifier,
navController: NavHostController,
startDestination: String
) {
val actions = remember(navController) { Actions(navController = navController) }
AnimatedNavHost(
modifier = modifier,
navController = navController,
startDestination = startDestination
) {
composable(
route = Destinations.Welcome.WELCOME_ROUTE,
enterTransition = {
when (initialState.destination.route) {
Destinations.Welcome.WELCOME_LOGIN_ROUTE ->
slideIntoContainer(towards = AnimatedContentScope.SlideDirection.Left, animationSpec = tween(700))
else -> null
}
},
exitTransition = {
when (targetState.destination.route) {
Destinations.Welcome.WELCOME_LOGIN_ROUTE ->
slideOutOfContainer(towards = AnimatedContentScope.SlideDirection.Left, animationSpec = tween(700))
else -> null
}
},
popEnterTransition = {
when (initialState.destination.route) {
Destinations.Welcome.WELCOME_LOGIN_ROUTE ->
slideIntoContainer(towards = AnimatedContentScope.SlideDirection.Right, animationSpec = tween(700))
else -> null
}
},
popExitTransition = {
when (targetState.destination.route) {
Destinations.Welcome.WELCOME_LOGIN_ROUTE ->
slideOutOfContainer(towards = AnimatedContentScope.SlideDirection.Right, animationSpec = tween(700))
else -> null
}
}
) {
WelcomeScreen(
navigateToLogin = actions.navigateToWelcomeLogin,
navigateToRegister = actions.navigateToWelcomeRegister,
)
}
composable(
route = Destinations.Welcome.WELCOME_LOGIN_ROUTE,
enterTransition = {
when (initialState.destination.route) {
Destinations.Welcome.WELCOME_ROUTE ->
slideIntoContainer(towards = AnimatedContentScope.SlideDirection.Left, animationSpec = tween(700))
else -> null
}
},
exitTransition = {
when (targetState.destination.route) {
Destinations.Welcome.WELCOME_ROUTE ->
slideOutOfContainer(towards = AnimatedContentScope.SlideDirection.Left, animationSpec = tween(700))
else -> null
}
},
popEnterTransition = {
when (initialState.destination.route) {
Destinations.Welcome.WELCOME_ROUTE ->
slideIntoContainer(towards = AnimatedContentScope.SlideDirection.Right, animationSpec = tween(700))
else -> null
}
},
popExitTransition = {
when (targetState.destination.route) {
Destinations.Welcome.WELCOME_ROUTE ->
slideOutOfContainer(towards = AnimatedContentScope.SlideDirection.Right, animationSpec = tween(700))
else -> null
}
}
) {
WelcomeLoginScreen(
// Arguments will be passed to navigate to the home screen or other
)
}
}
}
class Actions(val navController: NavHostController) {
// Welcome
val navigateToWelcome = {
navController.navigate(Destinations.Welcome.WELCOME_ROUTE)
}
val navigateToWelcomeLogin = {
navController.navigate(Destinations.Welcome.WELCOME_LOGIN_ROUTE)
}
}
For simplicity's sake, you can assume that the screens are juste a box with a button in the middle which executes the navigation when they are clicked.
The accompanist version I am using is 0.24.1-alpha (the latest as of this question) and I am using compose version 1.2.0-alpha02 and kotlin 1.6.10.
In terms of animation, the only difference I can see with the accompanist samples is that I don't pass the navController to the screens but I don't see how that could be an issue.
And in terms of using the system back which should return to a previous, I'm genuinely stuck in terms of what could cause the navigation to close the app instead of going back. On other projects, the system back works just fine but not with this one. Is the use of the accompanist navigation incompatible ? I'm not sure.
Any help is appreciated!
I found the source of the issue.
The fact that I was setting the startDestination parameter to navBackStackEntry?.destination?.route ?: currentRoute meant that each change to the navBackStackEntry recomposed the MyHomeNavGraph and hence the backstack was reset upon the recomposition.
Note to self, watch out when copying navigation from multiple sources!

How to change icon if selected and unselected in android jetpack compose for NavigationBar like selector we use in xml for selected state?

I want to use outlined and filled icons based on selected state in NavigationBar just like google maps app, using jetpack compose. In case of xml we use selector so what do we use for compose ?
Here is my code ->
MainActivity.kt
#ExperimentalMaterial3Api
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Handle the splash screen transition.
installSplashScreen()
setContent {
MyApp()
}
}
}
#ExperimentalMaterial3Api
#Composable
fun MyApp() {
MyTheme {
val items = listOf(
Screen.HomeScreen,
Screen.MusicScreen,
Screen.ProfileScreen
)
val navController = rememberNavController()
Scaffold(
bottomBar = {
NavigationBar {
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentDestination = navBackStackEntry?.destination
items.forEach { screen ->
NavigationBarItem(
icon = {
Icon(
screen.icon_outlined,
contentDescription = screen.label.toString()
)
},
label = { Text(stringResource(screen.label)) },
selected = currentDestination?.hierarchy?.any { it.route == screen.route } == true,
onClick = {
navController.navigate(screen.route) {
// Pop up to the start destination of the graph to
// avoid building up a large stack of destinations
// on the back stack as users select items
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
// Avoid multiple copies of the same destination when
// reselecting the same item
launchSingleTop = true
// Restore state when reselecting a previously selected item
restoreState = true
}
}
)
}
}
}
) { innerPadding ->
NavHost(
navController,
startDestination = Screen.HomeScreen.route,
Modifier.padding(innerPadding)
) {
composable(route = Screen.HomeScreen.route) {
HomeScreen()
}
composable(route = Screen.MusicScreen.route) {
MusicScreen()
}
composable(route = Screen.ProfileScreen.route) {
ProfileScreen()
}
}
}
}
}
#ExperimentalMaterial3Api
#Preview(
showBackground = true, name = "Light mode",
uiMode = Configuration.UI_MODE_NIGHT_NO or Configuration.UI_MODE_TYPE_NORMAL
)
#Preview(
showBackground = true, name = "Night mode",
uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL
)
#Composable
fun DefaultPreview() {
MyApp()
}
Screen.kt
sealed class Screen(
val route: String,
#StringRes val label: Int,
val icon_outlined: ImageVector,
val icon_filled: ImageVector
) {
object HomeScreen : Screen(
route = "home_screen",
label = R.string.home,
icon_outlined = Icons.Outlined.Home,
icon_filled = Icons.Filled.Home
)
object MusicScreen : Screen(
route = "music_screen",
label = R.string.music,
icon_outlined = Icons.Outlined.LibraryMusic,
icon_filled = Icons.Filled.LibraryMusic,
)
object ProfileScreen : Screen(
route = "profile_screen",
label = R.string.profile,
icon_outlined = Icons.Outlined.AccountCircle,
icon_filled = Icons.Filled.AccountCircle,
)
}
HomeScreen.kt
#Composable
fun HomeScreen() {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center,
) {
Surface(color = MaterialTheme.colorScheme.background) {
Text(
text = "Home",
color = Color.Red,
fontSize = MaterialTheme.typography.displayLarge.fontSize,
fontWeight = FontWeight.Bold
)
}
}
}
#Preview(
showBackground = true, name = "Light mode",
uiMode = Configuration.UI_MODE_NIGHT_NO or Configuration.UI_MODE_TYPE_NORMAL
)
#Preview(
showBackground = true, name = "Night mode",
uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL
)
#Composable
fun HomeScreenPreview() {
HomeScreen()
}
Do I still need to use selector xml or there is alternative way in jetpack compose?
Yeah, you just make a simple if statement based on selected state, like this:
items.forEach { screen ->
val selected = currentDestination?.hierarchy?.any { it.route == screen.route } == true
NavigationBarItem(
icon = {
Icon(
if (selected) screen.icon_filled else screen.icon_outlined,
contentDescription = screen.label.toString()
)
},
selected = selected,
)
}

How to hide bottom navigation bar while scrolling down and show it while scrolling up in jetpack compose?

I'm creating a simple app with bottom navigation bar. I want to hide bottom navigation bar while scrolling down and show it while scrolling up in a composable screen.
Any help would be appreciated. Please do let me know if you need any more code. I have attached all the code that I think are relevant to this problem.
This is my bottom navigation bar.
#Composable
fun BottomBar(navController: NavController) {
val items = listOf(
NavigationItem.Home,
NavigationItem.Search
)
BottomNavigation(
backgroundColor = MaterialTheme.colors.DarkRed,
contentColor = Color.White
) {
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
items.forEach { item ->
BottomNavigationItem(
selected = currentRoute == item.route,
icon = {
Icon(
imageVector = item.icon,
contentDescription = "Icon",
modifier = Modifier.size(28.dp)
)
},
alwaysShowLabel = false,
selectedContentColor = Color.White,
unselectedContentColor = Color.White.copy(0.4f),
onClick = {
navController.navigate(item.route){
// Pop up to the start destination of the graph to
// avoid building up a large stack of destinations
// on the back stack as users select items
navController.graph.startDestinationRoute?.let{route ->
popUpTo(route){
saveState = true
}
}
// Avoid multiple copies of the same destination when
// reselecting the same item
launchSingleTop = true
// Restore state when reselecting a previously selected item
restoreState = true
}
}
)
}
}
}
This is my Main Screen
#Composable
fun MainScreen(){
val navController = rememberNavController()
Scaffold(topBar = {
ActionBar("Books")
},
bottomBar = {
BottomBar(navController)
}){
NavigationGraph(navController = navController)
}
}
And this NavigationGraph
#Composable
fun NavigationGraph(navController: NavHostController){
NavHost(navController = navController, startDestination = NavigationItem.Home.route ){
composable(NavigationItem.Home.route){
HomeScreen()
}
composable(NavigationItem.Search.route){
SearchScreen()
}
}
}
You can use a LazyListState to track the state of the list and only show the BottomBar when the scrollState index is initial. This can be done by:
For LazyColumn:
#Composable
fun HomeScreen(scrollState: LazyListState) {
LazyColumn(
state = scrollState,
) {
...
}
}
For NavigationGraph:
#Composable
fun NavigationGraph(navController: NavHostController, scrollState: LazyListState){
NavHost(navController = navController, startDestination = NavigationItem.Home.route ){
composable(NavigationItem.Home.route){
HomeScreen(scrollState = scrollState)
}
composable(NavigationItem.Search.route){
SearchScreen()
}
}
}
In the MainScreen:
#Composable
fun MainScreen(){
val navController = rememberNavController()
val scrollState = rememberLazyListState()
Scaffold(topBar = {
ActionBar("Books")
},
bottomBar = {
if(scrollState.firstVisibleItemIndex == 0){
BottomBar(navController)
}
}){
NavigationGraph(navController = navController, scrollState = scrollState)
}
}
This way the BottomBar will only show up when the list is at top.

Categories

Resources