Reputation: 81
I am trying to change the background color of TopAppBar but my TopAppBar doesn't get displayed. I have added the code below. I have added the required Modifier so it can show the background color as Magenta but it doesn't show any color. I am not even sure it's displaying the TopAppBar
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import com.example.movieapp.ui.theme.MovieAppTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApp()
}
}
}
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MyApp() {
MovieAppTheme {
Scaffold(topBar = {
MyTopAppBar()
}) {
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MyTopAppBar() {
TopAppBar(title = {Text(text = "Hello")},
Modifier.background(color = Color.Red)
)
}
Upvotes: 2
Views: 1599
Reputation: 1927
Please remove Modifier.background from your MyTopAppBar function and add below code :
fun MyTopAppBar() {
TopAppBar(
title = { Text(text = "Hello") },
colors = TopAppBarDefaults.topAppBarColors(
containerColor = Color.Magenta
)
)
}
Upvotes: 0
Reputation: 1652
You have to use the TopAppBarColors
TopAppBar(title = {Text(text = "Hello")}, colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Red))
BTW regarding the "I'm not sure it's even displaying it" there's an easy solution: the layout inspector :)
Upvotes: 3