-
-
Save hector6872/634e5039a9255c20e2cacbccc65881fc to your computer and use it in GitHub Desktop.
Jetpack Compose Simple calendar
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Composable | |
private fun Calendar( | |
modifier: Modifier = Modifier, | |
date: LocalDate | |
) { | |
val firstDate = with(date) { | |
val firstOfMonth = withDayOfMonth(1) | |
val firstDayOfFirstWeek = firstOfMonth.dayOfWeek.value | |
firstOfMonth.minusDays(firstDayOfFirstWeek.toLong()) | |
} | |
val daysOfWeek = DateFormatSymbols().shortWeekdays.drop(1).run { | |
if (!isSundayFirstDayOfWeek()) this.rotateLeft(1) else this | |
} | |
Column(modifier = modifier.fillMaxWidth()) { | |
Row(modifier = Modifier | |
.fillMaxWidth() | |
.padding(bottom = AppTheme.dimens.paddingSmall)) { | |
daysOfWeek.forEach { dayOfWeek -> | |
Text( | |
text = dayOfWeek, | |
modifier = Modifier.weight(1f), | |
textAlign = TextAlign.Center, | |
maxLines = 1, | |
style = AppTheme.typography.caption | |
) | |
} | |
} | |
LazyVerticalGrid(columns = GridCells.Fixed(count = DAYS_IN_A_WEEK)) { | |
items(DAYS_IN_A_WEEK * 6) { index -> // 6 rows | |
val day = firstDate.plusDays(index.toLong()).run { | |
if (!isSundayFirstDayOfWeek()) this.plusDays(1) else this | |
} | |
val isInCurrentMonth = day.month == date.month | |
Text( | |
text = day.dayOfMonth.toString(), | |
textAlign = TextAlign.Center, | |
color = when { | |
day.isToday() -> AppTheme.colors.primary | |
isInCurrentMonth -> Color.Unspecified | |
else -> AppTheme.colors.outline | |
}, | |
fontWeight = if (day.isToday()) FontWeight.Bold else null, | |
style = AppTheme.typography.caption | |
) | |
} | |
} | |
} | |
} | |
private const val DAYS_IN_A_WEEK = 7 | |
private fun isSundayFirstDayOfWeek(): Boolean = WeekFields.of(Locale.getDefault()).firstDayOfWeek.isSunday() | |
private fun DayOfWeek.isSunday(): Boolean = this == DayOfWeek.SUNDAY | |
private fun <TYPE> List<TYPE>.rotateLeft(n: Int): List<TYPE> = when { | |
n.isGreaterThanZero() && n < this.size -> drop(n) + take(n) | |
else -> this | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment