Search code examples
androidandroid-jetpack-compose

FloatingActionButton Alignment Issue in E-commerce Book App


I'm working on an Android e-commerce app for selling books, and I'm facing a challenge with the FloatingActionButton (FAB) placement. My Setup:

I have a persistent BottomAppBar throughout the app. I want the FAB to be positioned at the bottom right corner of the screen, above the BottomAppBar. The Problem:

If I place the FAB code in the homeScreen.kt file, it doesn't appear at all. If I put the code in the BottomAppBar.kt file, I can't seem to align it correctly to the bottom right corner. What I've Tried:

I've tried placing the code into HomeScreen.kt file but the button is hidden. and if i place the code into BottomAppBar.kt file then its not aligned properly. Screenshot of the App Code placed into BottomAppBar.kt Screenshot of the app code placed into HomeScreen.kt

What I Need Help With:

How can I make the FAB visible and aligned to the bottom right corner above the BottomAppBar, regardless of the screen where the FAB is needed?

I'm attaching GitHub Link BookNest.In

Here is the root Composable:

@Composable
fun AppNavigation() {
    val navController = rememberNavController()

    MainLayout(navController) { paddingValues ->
        NavHost(navController = navController, startDestination = ScreenRoutes.HOME) {
            composable(ScreenRoutes.HOME) { HomeScreen(navController) }
            composable(ScreenRoutes.ACCOUNT) { AccountScreen(navController) }
            composable(ScreenRoutes.NOTIFICATIONS) { NotificationsScreen(navController) }
            composable(ScreenRoutes.MENU) { MenuScreen(navController) }
        }
    }
}

And the MainLayout looks like this:

@Composable
fun MainLayout(navController: NavHostController, content: @Composable (PaddingValues) -> Unit) {
    Scaffold(
        bottomBar = { MyBottomAppBar(navController) },
        content = content
    )
}

Solution

  • If you want the FAB to be shown no matter which screen is displayed in the NavHost, then you should add it to the Scaffold in the MainLayout Composable. The Scaffold has a dedicated slot for placing a FloatingActionButton:

    @Composable
    fun MainLayout(navController: NavHostController, content: @Composable (PaddingValues) -> Unit) {
        Scaffold(
            floatingActionButton = {
                FloatingActionButton(
                    onClick = { /** navController.navTo(...) **/ },
                ) {
                    Icon(Icons.Filled.ShoppingCart, "Cart")
                }
            },
            floatingActionButtonPosition = FabPosition.End,
            bottomBar = { MyBottomAppBar(navController) },
            content = content
        )
    }
    

    This approach works well when the FAB should perform the same action, no matter on which screen you currently are. If you want your FAB to perform different actions depending on the screen, you will need a more advanced logic.