androidandroid-jetpack-composeandroid-compose-appbar

Change TopAppBar background color from themes.xml


In Jetpack Compose, TopAppBar shows default background color irrespective of what we added to themes.xml.

So how can we change TopAppBar background color from themes.xml so it's applied globally to the App?

TopAppBar(
    title = { Text("Activity") },
    navigationIcon = {
        IconButton(onClick = { onBackPressed() }) {
            Icon(Icons.Filled.ArrowBack, contentDescription = null)
        }
    }
)

themes.xml

<style name="Theme.MyApplication" parent="Theme.MaterialComponents.DayNight">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@android:color/black</item>
        <item name="colorPrimaryVariant">@android:color/holo_orange_dark</item>
        <item name="colorOnPrimary">@android:color/white</item>
</style>

enter image description here

Note : we can change it through backgroundColor attribute of TopAppBar but here I want to achieve it globally.


Solution

  • For the TopAppBar and the other composables the basis of theming is the MaterialTheme composable and not the AppCompat/MaterialComponents XML themes.

    The TopAppBar uses the backgroundColor attribute.
    The default value is defined by MaterialTheme.colors.primarySurface.

    You can change these colors globally defining your theme adding your Colors and passing them to a MaterialTheme:

    private val LightColors = lightColors(
        primary = Yellow500,
        //...
    )
    

    Otherwise you can simply use :

    TopAppBar(
        title = { Text("Activity") },
        backgroundColor = /*...*/,
        /* ... */
    )
    

    If you want to use the AppCompat XML themes in Jetpack Compose you can use the AppCompat Compose Theme Adapter provided by the accompanist library.