如何在此日期选择器中只允许选择几个日期?

问题描述 投票:0回答:1

我正在使用此撰写库作为我的日期选择器:https://github.com/maxkeppeler/sheets-compose-dialogs

可组合项仅接受不允许的日期,如下所示:

val disabledDates = listOf(
    LocalDate.now().plusDays(3),
    LocalDate.now().plusDays(5),
    LocalDate.now().plusDays(7),
)

CalendarView(
    useCaseState = rememberUseCaseState(),
    config = CalendarConfig(
        style = CalendarStyle.MONTH,
        disabledDates = disabledDates,
        boundary = LocalDate.now()..LocalDate.now().plusYears(10),
    ),
    selection = CalendarSelection.Date { newDate ->
        selectedDate.value = newDate
    },
)

问题是我只需要传递几个允许的日期。我怎样才能实现这个目标? 有没有办法将允许的日期转换为不允许的日期列表或其他内容?

android kotlin datepicker android-jetpack-compose
1个回答
0
投票

由于此组合仅允许禁用给定

boundary
中的某些日期,因此无法提供所有日期的列表减去您想要允许的日期。

我们假设示例中的 disabledDates 实际上是 允许的日期。然后,您需要从日历应显示的范围中删除这些日期 (

boundary
),以便可以将其作为
disabledDates
传递。

只有一个问题:

boundary
是一个
ClosedRange
。它仅由开始值和结束值组成,中间没有值,因此无法转换为列表。为了填补这个空白,我们需要一个用于这样一个范围的迭代器:

fun ClosedRange<LocalDate>.toIterable(): Iterable<LocalDate> = Iterable {
    object : Iterator<LocalDate> {
        private var nextDate = start

        override fun hasNext(): Boolean = nextDate <= endInclusive

        override fun next(): LocalDate = nextDate
            .also { nextDate = nextDate.plusDays(1) }
    }
}

现在我们可以从日期范围中删除允许的日期,如下所示:

boundary.toIterable() - allowedDates

将所有内容放在一起,看起来像这样:

val boundary = LocalDate.now()..LocalDate.now().plusYears(10)

val allowedDates = setOf(
    LocalDate.now().plusDays(3),
    LocalDate.now().plusDays(5),
    LocalDate.now().plusDays(7),
)

val disabledDates = boundary.toIterable() - allowedDates

CalendarView(
    useCaseState = rememberUseCaseState(),
    config = CalendarConfig(
        style = CalendarStyle.MONTH,
        disabledDates = disabledDates,
        boundary = boundary,
    ),
    selection = CalendarSelection.Date { newDate ->
        selectedDate.value = newDate
    },
)
© www.soinside.com 2019 - 2024. All rights reserved.