[英]How to implement a change of week from one to another android
Faced with such a task: I am making an app for a university, where every week (starts on Monday at 00:00) has its own name: numerator and denominator.面对这样的任务:我正在为一所大学制作一个应用程序,其中每个星期(从星期一 00:00 开始)都有自己的名称:分子和分母。 Let's say the current week is the numerator, the next one will be the denominator, then the numerator again, and so on.
假设当前周是分子,下一周是分母,然后又是分子,依此类推。
I do not understand how it is possible to make the type (numerator or denominator) displayed on my fragment every week, well, it is desirable that at 00:00 on Sunday the week changed to the numerator or denominator, respectively.我不明白如何使每周显示在我的片段上的类型(分子或分母)成为可能,好吧,最好在星期日的 00:00 分别更改为分子或分母。 I am using Kotlin
我正在使用 Kotlin
I would do this in a ViewModel.我会在 ViewModel 中做到这一点。 Expose a LiveData with Boolean value where true/false correspond with numerator week or denominator week.
使用布尔值公开 LiveData,其中 true/false 对应于分子周或分母周。 Choose an arbitrary Monday date to use as your baseline to calculate the current day from.
选择一个任意的星期一日期作为计算当天的基准。 I'm arbitrarily using this week's Monday as this baseline epoch.
我随意使用本周的星期一作为这个基准时期。
However, this approach assumes that the university's calendar never, ever breaks the pattern.然而,这种方法假设大学的日历永远不会打破这种模式。 If they have an inconsistent pattern, you will need a data table to look up what value to use.
如果它们的模式不一致,您将需要一个数据表来查找要使用的值。
class MyViewModel : ViewModel() {
companion object {
private val WEEK_TYPE_BASELINE_DAY = LocalDate.of(2021, 11, 1)
}
private val mutableWeekType = MutableLiveData<Boolean>()
val weekType: LiveData<Boolean> get() = mutableWeekType
init {
updateCurrentWeekType()
}
private fun updateCurrentWeekType() {
val today = LocalDate.now()
val weeks = Duration.between(WEEK_TYPE_BASELINE_DAY, today).toDays() / 7L
mutableWeekType.value = weeks % 2 == 0L
// In case the week changes while this ViewModel is alive,
// plan the next update.
val nextMonday = today.with(TemporalAdjusters.next(DayOfWeek.MONDAY))
val nextMondayMidnight = LocalDateTime.of(nextMonday, LocalTime.MIDNIGHT)
val timeToNextChange = Duration.between(LocalDateTime.now(), nextMondayMidnight).toMillis()
viewModelScope.launch {
delay(timeToNextChange)
updateCurrentWeekType()
}
}
}
The fragment can observe weekType
and modify the text of any UI element based on whether it receives true or false. weekType
可以观察weekType
并根据接收到的 true 或 false 来修改任何 UI 元素的文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.