android-jetpack-compose

Material 3 Top Bar container color not change on scroll


The top app bar container color not change on scroll, the color keep the same. Working with XML views it works fine, but compose doesn't.

If is a bug or the featured was not ported for compose yet, but if ins't a bug, i'm miss something in the code?

I'm using version 1.0.1 of the material 3 library.

Sample code:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        WindowCompat.setDecorFitsSystemWindows(window, false)
        setContent {
            val uiController = rememberSystemUiController()
            uiController.setStatusBarColor(Color.Transparent)
            MyApplication5Theme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    Scaffold(
                        topBar = {
                            TopAppBar(
                                title = { Text("k") },
                                modifier = Modifier.statusBarsPadding(),
                            )
                        }
                    ) {
                        LazyColumn(
                            modifier = Modifier
                                .fillMaxSize()
                                .padding(it)
                        ) {
                            items((1..100).toList()) {
                                Text(it.toString(), modifier = Modifier.padding(8.dp))
                            }
                        }
                    }
                }
            }
        }
    }
}

I tried create a simple layout with a top app bar and a lazy column, i expected top app bar container color changes on scroll of the lazy column, but the color keep the same.


Solution

  • The TopAppBar composable has a scrollBehavior argument, which is null be default. If you leave it null, it will not react to scroll events, you have to connect it with your scrollable component. You can do that like this:

    val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior()
    Scaffold(
        modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
        topBar = { TopAppBar(scrollBehavior = scrollBehavior, ...) },
    ) { LazyColumn() {} }