9

我有一个自定义的线性布局,其中包含DatePickerTimePicker部件。这用作DateTime选择器。我想通过setMaxDate()and来限制 DatePicker setMinDate()。我已经做好了:

dp.setMaxDate(new DateTime().minusDays(1).getMillis());
dp.setMinDate(new DateTime().minusDays(30).getMillis());

当对话框出现时,超出此范围的日期实际上是灰色的。但我仍然可以选择一个灰色的日期。我偶然发现了这一点。但是,其中包含 datepicker 的自定义布局的解决方法是什么?

4

3 回答 3

14

给未来的读者!

实际上,使用新的android 材料设计组件可以使用MaterialDatePicker. 超出允许范围的日期是不可选择的。

受限制的日期选择器范围


脚步

1. 将材料依赖添加到模块的 gradle 文件中

implementation 'com.google.android.material:material:1.1.0-beta01'

2.更改应用主题以继承材料主题的版本。

前任:

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">

3. 使用以下代码启动对话框。

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        setupRangePickerDialog()

    }

    private fun setupRangePickerDialog() {
        val builderRange = MaterialDatePicker.Builder.dateRangePicker()

        builderRange.setCalendarConstraints(limitRange().build())
        val pickerRange = builderRange.build()
        pickerRange.show(supportFragmentManager, pickerRange.toString())
    }


    /*
    Limit selectable range to Oct 17 - Nov 20 2019
     */
    private fun limitRange(): CalendarConstraints.Builder {

        val constraintsBuilderRange = CalendarConstraints.Builder()

        val calendarStart: Calendar = GregorianCalendar.getInstance()
        val calendarEnd: Calendar = GregorianCalendar.getInstance()

        val year = 2019

        calendarStart.set(year, 10, 17)
        calendarEnd.set(year, 11, 20)

        val minDate = calendarStart.timeInMillis
        val maxDate = calendarEnd.timeInMillis

        constraintsBuilderRange.setStart(minDate)
        constraintsBuilderRange.setEnd(maxDate)

        constraintsBuilderRange.setValidator(RangeValidator(minDate, maxDate))

        return constraintsBuilderRange
    }


}

class RangeValidator(private val minDate:Long, private val maxDate:Long) : CalendarConstraints.DateValidator{


    constructor(parcel: Parcel) : this(
        parcel.readLong(),
        parcel.readLong()
    )

    override fun writeToParcel(dest: Parcel?, flags: Int) {
        TODO("not implemented")
    }

    override fun describeContents(): Int {
        TODO("not implemented")
    }

    override fun isValid(date: Long): Boolean {
        return !(minDate > date || maxDate < date)

    }

    companion object CREATOR : Parcelable.Creator<RangeValidator> {
        override fun createFromParcel(parcel: Parcel): RangeValidator {
            return RangeValidator(parcel)
        }

        override fun newArray(size: Int): Array<RangeValidator?> {
            return arrayOfNulls(size)
        }
    }

}
于 2019-10-12T13:57:12.860 回答
12

材料组件库提供MaterialDatePicker.
您可以使用 aDateValidator来限制选择。
特别是您可以使用内置的验证器:

  • DateValidatorPointForward 启用从给定点向前的日期
  • DateValidatorPointBackward仅启用给定点之前的日期。

就像是:

MaterialDatePicker.Builder<Pair<Long, Long>> builderRange = MaterialDatePicker.Builder.dateRangePicker();
CalendarConstraints.Builder constraintsBuilderRange = new CalendarConstraints.Builder();

//....define min and max for example with LocalDateTime and ZonedDateTime or Calendar

CalendarConstraints.DateValidator dateValidatorMin = DateValidatorPointForward.from(min.getTimeInMillis());
CalendarConstraints.DateValidator dateValidatorMax = DateValidatorPointBackward.before(max.getTimeInMillis());

ArrayList<CalendarConstraints.DateValidator> listValidators =
            new ArrayList<CalendarConstraints.DateValidator>();
listValidators.add(dateValidatorMin);
listValidators.add(dateValidatorMax);
CalendarConstraints.DateValidator validators = CompositeDateValidator.allOf(listValidators);
constraintsBuilderRange.setValidator(validators);

builderRange.setCalendarConstraints(constraintsBuilderRange.build());
MaterialDatePicker<Pair<Long, Long>> pickerRange = builderRange.build();
pickerRange.show(getSupportFragmentManager(), pickerRange.toString());

在此处输入图像描述

于 2020-05-29T06:47:05.897 回答
4

如果有人想要 RangeValidator(上面发布)但代码更少:(添加了@Parcelize 注释)

@Parcelize
internal class RangeValidator(
private var minDate: Long = 0,
private var maxDate: Long = 0) : DateValidator {

     override fun isValid(date: Long): Boolean {
         return !(minDate > date || maxDate < date)
     }
}
于 2020-12-07T14:42:14.427 回答