我有一个 Kotlin 代码可以在白天和晚上显示图像(imageday.png 和 imagenight.png) 这是代码:
private fun getBackgroundImageByTime(time: LocalTime): Int =
when (time.hour) {
in 6..18 -> R.drawable.imageday
else -> R.drawable.imagenight
}
现在我正在尝试在上述时间按一周中的几天加载图像。
我的图像是:monday_imageday、monday_imagenight、tuesday_imageday、tuesday_imagenight 等... 如何以编程方式从可绘制文件夹加载这些图像取决于今天的日期。 如果今天是星期二,则应分别加载 imageday 和 imagenight。
我在这里感到震惊,请有人帮忙。
如果你的最小SDK是26,你可以使用
LocalDateTime
。
val dateTime = LocalDateTime.now()
val dayOfWeek = dateTime.dayOfWeek
val hour = dateTime.hour
val image = when(dayOfWeek) {
DayOfWeek.MONDAY -> if (hour in 6..18) R.drawable.monday_imageday else R.drawable.monday_imagenight
DayOfWeek.TUESDAY -> if (hour in 6..18) R.drawable.tuesday_imageday else R.drawable.tuesday_imagenight
DayOfWeek.WEDNESDAY -> if (hour in 6..18) R.drawable.wednesday_imageday else R.drawable.wednesday_imagenight
DayOfWeek.THURSDAY -> if (hour in 6..18) R.drawable.thursday_imageday else R.drawable.thursday_imagenight
DayOfWeek.FRIDAY -> if (hour in 6..18) R.drawable.friday_imageday else R.drawable.friday_imagenight
DayOfWeek.SATURDAY -> if (hour in 6..18) R.drawable.saturday_imageday else R.drawable.saturday_imagenight
DayOfWeek.SUNDAY -> if (hour in 6..18) R.drawable.sunday_imageday else R.drawable.sunday_imagenight
}
如果您的最低 SDK 低于 26,您可以使用
Calendar
实现向后兼容。
val calendar = Calendar.getInstance()
val dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)
val hour = calendar.get(Calendar.HOUR_OF_DAY)
val image = when(dayOfWeek) {
1 -> if (hour in 6..18) R.drawable.monday_imageday else R.drawable.monday_imagenight
2 -> if (hour in 6..18) R.drawable.tuesday_imageday else R.drawable.tuesday_imagenight
3 -> if (hour in 6..18) R.drawable.wednesday_imageday else R.drawable.wednesday_imagenight
4 -> if (hour in 6..18) R.drawable.thursday_imageday else R.drawable.thursday_imagenight
5 -> if (hour in 6..18) R.drawable.friday_imageday else R.drawable.friday_imagenight
6 -> if (hour in 6..18) R.drawable.saturday_imageday else R.drawable.saturday_imagenight
7 -> if (hour in 6..18) R.drawable.sunday_imageday else R.drawable.sunday_imagenight
}