4

How can a color resource be used to change the background colour for a MD3 top app bar in Jetpack Compose?

Understandably, a colors property is available but it's not clear what to use for the above.

Color.kt

val MyColor = Color(0,5,5,255)

MainActivity.kt

MediumTopAppBar(title = {Text(text = "")})
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
wbk727
  • 8,017
  • 12
  • 61
  • 125

2 Answers2

8

The colors parameter is supposed to be used like so.

There's usually a Default Companion for these things, which provides a convenience function for modifying colors. For example, the default companion for Top bar colors is just TopAppBarDefaults.

Since you are referring to medium bars, we'll use the following

TopAppBarDefaults.mediumTopAppBarColors(
containerColor = Color(...) //Add your own color here, just to clarify.
)

These functions usually provide a containerColor and a contentColor parameter by default.

Solving your problems is... Super-easy, barely an inconvenience.

Richard Onslow Roper
  • 5,477
  • 2
  • 11
  • 42
  • This is the way to **modify** the defaults. The `Color(...)` I typed there is your own color, whichever you wish for the background of the top bar to be – Richard Onslow Roper May 02 '22 at 10:46
  • Sir you are not learning from your mistakes. You asked this previously as well. I pointed you just need to store it in a variable ABOVE the Composable declaration, and then you can use it. Also, `colorResource` is not the correct way of handling colors and theming in Compose. They are supposed to go in the Theme.kt file, but that's beyond the scope of this question. Just before calling your Composable, do something like `val a = colorResource(...)` then use pass `a` as the `containerColor`. Try to retain this info in memory. Just asking everything and not learning won't likely help you much. – Richard Onslow Roper May 02 '22 at 11:23
  • That's a separate question, sir. Is the current one resolved? Just access the resource as I described above and please let me know. – Richard Onslow Roper May 02 '22 at 11:39
  • How to change this for the whole app instead of just one composable? Can this be done in the theme? – David Nov 04 '22 at 07:50
  • Look at the source of the Composable in concern to find which colour it picks up by default. Most likely it's the surface material color. So, just modify that one colour and you're good to go. If you don't want to modify a color used extensively by many Composables, just create a new color in your custom theme Composable, then simply create a custom Composable for the appbar, reading that custom variable from there. – Richard Onslow Roper Nov 04 '22 at 14:57
0

If you are using material3 and changing background color doesn't work, there is an issue in androidx.compose.material3:material3, and you need to upgrade it to androidx.compose.material3:material3:1.2.0-alpha06 or newer versions to fix the background issue in mediumTopAppBar or largeTopAppBar.