mml ch
mml ch

Reputation: 11

Can't keep the color of topBar and CenterAlignedTopAppBar constant when scrolling

I can't keep the color of topBar and CenterAlignedTopAppBar unchanged when scrolling

I tried

colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
    containerColor = MaterialTheme.colorScheme.surface
)

But it can only set the color when it is not scrolling Then I looked up various materials and didn't find any useful methods This is my entire code:

val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(rememberTopAppBarState())

Scaffold(
    modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
    topBar = {
        CenterAlignedTopAppBar(
            title = {},
            modifier = Modifier.wrapContentHeight(),
            colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
                containerColor = MaterialTheme.colorScheme.surface // Set background color
            ),
            scrollBehavior = scrollBehavior,
        )
    },
)

Upvotes: 1

Views: 31

Answers (2)

tyg
tyg

Reputation: 15763

The color change is by design in a Material 3 Top app bar. It is used to better separate the app bar from the content when the content is in a scrolled state.

You already figured out how to change the container color when the content is not scrolled. If you want the app bar to also keep this color in the scrolled state then set scrolledContainerColor to the same color:

colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
    containerColor = MaterialTheme.colorScheme.surface, // Set background color
    scrolledContainerColor = MaterialTheme.colorScheme.surface // Set background color for scrolled state
), 

Upvotes: 0

Aida
Aida

Reputation: 1

first Remove the Scroll Behavior: Ensure that you are not using a scroll behavior that modifies the app bar's appearance when the content is scrolled. then Set the AppBar Colors: You can specify a constant color for the app bar without relying on the scrolling behavior.

Upvotes: 0

Related Questions