Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@bagus2x
Last active April 4, 2023 17:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bagus2x/979364d8a5f32e7600414f4612dea18d to your computer and use it in GitHub Desktop.
Save bagus2x/979364d8a5f32e7600414f4612dea18d to your computer and use it in GitHub Desktop.
custom calendar with jetpack compose & java.time
private val DaysInMonthCell = GridCells.Fixed(count = 7)
@Composable
fun Calendar(
modifier: Modifier = Modifier,
localDateTime: LocalDateTime
) {
val firstDate = remember(localDateTime) {
with(localDateTime) {
val firstOfMonth = withDayOfMonth(1)
val firstDayOfFirstWeek = firstOfMonth.dayOfWeek.value
firstOfMonth.minusDays(firstDayOfFirstWeek.toLong())
}
}
val daysOfWeek = remember {
DateFormatSymbols().shortWeekdays.drop(1)
}
Column(modifier = modifier.fillMaxSize()) {
Row(modifier = Modifier.fillMaxWidth()) {
daysOfWeek.forEach { dayOfWeek ->
key(dayOfWeek) {
Text(
text = dayOfWeek,
modifier = Modifier.weight(1F),
textAlign = TextAlign.Center,
maxLines = 1
)
}
}
}
LazyVerticalGrid(columns = DaysInMonthCell) {
items(42) { index ->
val date = firstDate.plusDays(index.toLong())
val isInCurrentMonth = date.month == localDateTime.month
val isToday =
date.dayOfYear == LocalDateTime.now().dayOfYear && date.year == LocalDateTime.now().year
Text(
text = date.dayOfMonth.toString(),
textAlign = TextAlign.Center,
color = if (isToday)
Color.Red
else
if (isInCurrentMonth)
MaterialTheme.colors.primary
else
MaterialTheme.colors.secondary
)
}
}
}
}
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyHabitTheme {
Icons.Outlined.Create
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
Column {
var localDateTime by remember { mutableStateOf(LocalDateTime.now()) }
Row(
horizontalArrangement = Arrangement.SpaceEvenly,
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Button(onClick = { localDateTime = localDateTime.minusMonths(1) }) {
Text(text = "Prev")
}
Text(text = "${localDateTime.month.name} ${localDateTime.year}")
Button(onClick = { localDateTime = localDateTime.plusMonths(1) }) {
Text(text = "Next")
}
}
Calendar(localDateTime = localDateTime)
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment