Home > Blockchain >  Compose TopAppBar has no background color
Compose TopAppBar has no background color

Time:10-07

I want to add a TopAppBar to my Compose app, so I did the following:

@OptIn(ExperimentalMaterial3Api::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            AlternoTubeTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    Scaffold(
                        topBar = {
                            TopAppBar(
                                title = {
                                    Text(
                                        stringResource(id = R.string.app_name),
                                        maxLines = 1,
                                        overflow = TextOverflow.Ellipsis
                                    )
                                },
                            )
                        },
                        content = { innerPadding ->
                            MyAppTheme(modifier = Modifier.padding(innerPadding))
                        }
                    )
                }
            }
        }
    }

The issue is, when I run the app, there is no color to my TopAppBar:

enter image description here

Whereas on the preview images, the app bar does have colors:

enter image description here

Any help as to how I could get the right colors would be appreciated, I am stumped as to why this is happening.

CodePudding user response:

With M3 the default value of the background color in the TopAppBar is defined in the TopAppBarDefaults.smallTopAppBarColors() with the containerColor attribute. The default value is the surface color defined in your theme.

Check your theme or you can override it using something like:

TopAppBar(
    title = {
        Text(
            stringResource(id = R.string.app_name),
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
    },
    colors = TopAppBarDefaults.smallTopAppBarColors(containerColor = Yellow)
)
  • Related