我正在使用 Stackoverflow 上的上一个问题,使用 jetpack compose 中视图库的 DatePicker 来实现轮日期选择器。 我在导航到下一页之前得到的结果。
date_picker.xml
<DatePicker xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/black"
android:calendarTextColor="#FFFFFF"
android:calendarViewShown="false"
android:datePickerMode="spinner"
android:theme="@style/CustomDatePickerStyle" />
Android视图
@Composable
fun DatePicker(
onDateSelected: (Date) -> Unit
) {
AndroidView(
modifier = Modifier.fillMaxWidth(),
factory = { context ->
val view = LayoutInflater.from(context).inflate(R.layout.date_picker, null)
val datePicker = view.findViewById<DatePicker>(R.id.datePicker)
val calendar = Calendar.getInstance() // show today by default
datePicker.init(
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH)
) { _, year, monthOfYear, dayOfMonth ->
val date = Calendar.getInstance().apply {
set(year, monthOfYear, dayOfMonth)
}.time
onDateSelected(date)
}
datePicker
}
)
}
我就是这样使用的
DatePicker { date ->
validationViewModel.changeDateOfBirth(date)
}
这是validationViewModel
/** Date of Birth Validation */
var dateOfBirth by mutableStateOf(Date())
private set
@OptIn(ExperimentalCoroutinesApi::class)
val dateOfBirthError = snapshotFlow { dateOfBirth }
.mapLatest { validateAge.execute(dateOfBirth.toString().substring(30)) }
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = ValidationResult()
)
fun changeDateOfBirth(value: Date) {
dateOfBirth = value
}
主题.kt
private val colorScheme = lightColorScheme(
primary = green, // Your custom green color
onPrimary = Color.White, // Black text on green buttons
secondary = Color.White,
background = Color.Black,
onBackground = Color.White,
surface = Color.Black,
onSurface = Color.White
)
@Composable
fun SpotifyTheme(
content: @Composable () -> Unit
) {
val colorScheme = colorScheme
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
要在应用程序中仅添加深色主题,您只需将 lightColorScheme 更改为 darkColorScheme ,如下所示
private val DarkColorScheme = darkColorScheme(
primary = green, // Your custom green color
onPrimary = Color.White, // Black text on green buttons
secondary = Color.White,
background = Color.Black,
onBackground = Color.White,
surface = Color.Black,
onSurface = Color.White
)
最后您可以在 Material 主题中使用这个深色主题。
MaterialTheme(
colorScheme = DarkColorScheme,
typography = Typography,
content = content
)