限制Android DatePicker自定义对话框中的范围

时间:2016-03-15 06:48:01

标签: java android datepicker

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

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

当对话框出现时,超出此范围的日期实际上是灰色的。但我仍然可以选择一个灰色的日期。我偶然发现了this。但是,使用datepicker的自定义布局的工作是什么?

3 个答案:

答案 0 :(得分:5)

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

  • 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());

enter image description here

答案 1 :(得分:0)

供将来的读者使用!

实际上,使用新的android material design components可以使用MaterialDatePicker实现您想要的目标。并且日期超出允许范围是不可选择的。

restricted datepicker range


步骤

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)
        }
    }

}

答案 2 :(得分:0)

如果有人想要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)
     }
}