Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Jetpack compose app bar backbutton

getActionBar().setDisplayHomeAsUpEnabled(true) this i was using for normal android AppCompatActivity to switch between two or more activity.can any one tell me how to do this in jetpack Compose ?

like image 509
Kashinath Avatar asked Sep 11 '25 16:09

Kashinath


1 Answers

The other answer is correct for showing the back button. This is a slight alternative that uses TopAppBar composable instead.

I also ran into a similar issue. The main thing I wanted to solve was hiding the back button when you are at the root or if there is nothing left in backstack, since setDisplayHomeAsUpEnabled took care of that as long as you specified your parent.
Assuming you are using the nav controller with compose, you can do something like this

val navController = rememberNavController()
Scaffold(
    topBar = {
        TopAppBar(
            title = { Text(text = "app bar title") },
            navigationIcon = if (navController.previousBackStackEntry != null) {
                {
                    IconButton(onClick = { navController.navigateUp() }) {
                        Icon(
                            imageVector = Icons.Filled.ArrowBack,
                            contentDescription = "Back"
                        )
                    }
                }
            } else {
                null
            }

        )
    },
    content = {
        // Body content
    }
)

The key here is to set navigationIcon argument of TopAppBar to null when there is nothing in the back stack. This way the back arrow will be hidden when you are at the root and shown otherwise.

like image 104
Naveed Avatar answered Sep 13 '25 05:09

Naveed