I already setup custom color for Jetpack Compose theme, but when i call MaterialTheme.colorScheme.primary
it giving me the default purple color.
val primaryLight = Color(0xFF1F6A4E)
private val lightScheme = lightColorScheme(
primary = primaryLight
)
@Composable
fun AppTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> darkScheme
else -> lightScheme
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
And here's the usage:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
AppTheme{
Box(
Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.primary))
}
}
}
}
This is most likely due to the dynamic colors introduced in Android 12 (API level 31).
If you look at your theme you'll see that there are actually three cases in the when
statement:
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
darkTheme
else
If dynamic colors are activated in the theme (dynamicColor
) and the app currently runs on a device that supports dynamic colors (Build.VERSION_CODES.S
) then it skips your explicitly defined lightScheme
and darkScheme
and uses a dynamic color palette instead.
You can try running your app on a device with API level of 30 or below to see the difference.
If you want to deactivate dynamic colors regardless of the API level so your lightScheme
will always be used, then set the AppTheme
's parameter accordingly:
AppTheme(dynamicColor = false) {
Box(
Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.primary)
)
}
Alternatively you can declare the parameter to be false
by default or remove it (and the first when
case) entirely.