androidmaterial-designandroid-jetpack-composeandroid-jetpackmaterial-components-android

How to expand TopAppBar programmatically?


MediumTopAppBar and LargeTopAppBar have expanded and closed state.

EnterAlwaysScrollBehavior will immediately collapse when the content is pulled up, and will immediately appear when the content is pulled down. (from the doc)

If scrolled down and the page body content changes it'll still be in the closed state as expected. But I want to trigger an expanded state back when say content changed or a button is pressed without the user scrolling up.

What I need:

A method or workaround to change the TopAppBar state to expand.


Solution

  • Assuming you have the LargeTopAppBar scroll behaviour as

    val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior(rememberTopAppBarState())
    

    and the LargeTopAppBar as

    Scaffold(
                    topBar = {
                        LargeTopAppBar(
                            title = { Text(text = "title") },
                            scrollBehavior = scrollBehavior
                        )
                    },
                    floatingActionButton = {
                        FloatingActionButton(
                            onClick = {
                                if (scrollBehavior.state.heightOffset < 0.0) {
                                    //expand the LargeTopAppBar
                                    scrollBehavior.state.heightOffset = 0f
                                } else {
                                    //collapse the LargeTopAppBar
                                    scrollBehavior.state.heightOffset = -242f
                                }
    
                            }
                        ) {
                        }
                    },
                ) {}
    

    I tried setting the offset to -1000f, it still performs the same function