gpt4 book ai didi

android - 为 materialDatePicker 设置 180 天的日历限制

转载 作者:行者123 更新时间:2023-12-02 12:49:51 35 4
gpt4 key购买 nike

我正在使用 MaterialDatePicker对于 Android (Kotlin),需要确保开始日期和结束日期相隔不超过 180 天。我该如何为此编写约束?

最佳答案

您可以定义自定义 DateValidator :

public class RangeDateValidator implements CalendarConstraints.DateValidator {

private MaterialDatePicker rangePicker;
private final int numberOfDays;

public RangeDateValidator(int numberOfDays){
this.numberOfDays = numberOfDays;
}

public void setDatePicker(MaterialDatePicker rangePicker) {
this.rangePicker = rangePicker;
}

@Override
public boolean isValid(long date) {
Pair<Long,Long> selection = (Pair<Long, Long>) rangePicker.getSelection();
if (selection != null) {
Long startDate = selection.first;
if (startDate != null) {
long days = (numberOfDays-1) * TimeUnit.DAYS.toMillis(1);;
if (date > startDate + days)
return false;
if (date < startDate)
return false;
}
}
return true;
}
接着:
    MaterialDatePicker.Builder<Pair<Long, Long>> builder = 
MaterialDatePicker.Builder.dateRangePicker();


CalendarConstraints.Builder constraintsBuilderRange = new CalendarConstraints.Builder();
RangeDateValidator dateValidator = new RangeDateValidator(10);
constraintsBuilderRange.setValidator(dateValidator);
builder.setCalendarConstraints(constraintsBuilderRange.build());

MaterialDatePicker<Pair<Long, Long>> datePicker= builder.build();
dateValidator.setDatePicker(datePicker);
datePicker.show(getSupportFragmentManager(),datePicker.getTag());
enter image description here

关于android - 为 materialDatePicker 设置 180 天的日历限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63168092/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com