0

I use DatePicker from material3 with custom colors.

I want to change background color of DatePicker. As I understand I need to change actually the elevation overlay color of Surface. But how I can do it?

Here is my code:

@OptIn(ExperimentalMaterial3Api::class)
@Preview(showBackground = true, backgroundColor = 0xFFFFFFFF)
@Composable
fun DatePickerPreview() {
    val datePickerState = rememberDatePickerState(initialDisplayMode = DisplayMode.Picker)
    Surface(
        tonalElevation = 6.dp,
        contentColor = AppTheme.colors.textSecondary,
        modifier = Modifier.padding(16.dp),
        shape = MaterialTheme.shapes.extraLarge,
        ) {
        DatePicker(
            state = datePickerState,
            colors = AppDefaults.datePickerColors(),
            dateValidator = {
                DateTimeUtils.timestampToDate(it)?.isAfter(Date()) == false
            }
        )
    }
}

But background color of DatePicker now is the default material neutral color. I want to set my custom blue color for it instead of material purple, but with correctly calculated alpha like in material3. Explanation of material3 tonalElevation.

The overlay color comes from the primary color slot but I don't use MeterialTheme for my app, instead of this I use the my custom theme

And here is the result: enter image description here

tasjapr
  • 632
  • 4
  • 13
  • You can change background color of DatePicker by assigning `Modifier.background` to it. contentColor changes color of arrows. What do you mean by correctly calculated alpha? – Thracian Jun 13 '23 at 19:13
  • @Thracian Of course, I understand that I can set just the background color through a modifier, but that's not what I'm looking for. I want the color to match the set `tonalElevation` value. Here is the explanation of m3 elevation concept https://developer.android.com/jetpack/compose/designsystems/material3#elevation . I update question – tasjapr Jun 13 '23 at 20:59

1 Answers1

1

So, I solved this by locally using of MaterialTheme from material3 and overriding some colors:

@OptIn(ExperimentalMaterial3Api::class)
@Preview(showBackground = true, backgroundColor = 0xFFFFFFFF)
@Composable
fun DatePickerMaterialTheme() {
    val datePickerState = rememberDatePickerState(initialDisplayMode = DisplayMode.Picker)
    val validate: (Long) -> Boolean = remember { { DateTimeUtils.timestampToDate(it)?.isAfter(Date()) == false } }

    MaterialTheme(
        colorScheme = MaterialTheme.colorScheme.copy(
            surface = AppTheme.colors.surface,
            primary = AppTheme.colors.primary,
            onPrimary = AppTheme.colors.onPrimary
        )
    ) {
        Surface(
            tonalElevation = 6.dp,
            shape = MaterialTheme.shapes.extraLarge
        ) {
            DatePicker(
                state = datePickerState,
                dateValidator = validate
            )
        }
    }
}
tasjapr
  • 632
  • 4
  • 13