在日期选择器的Andr​​oid禁用过去的日期日期、过去、选择器、Andr

2023-09-04 23:34:53 作者:下一季有你

我需要禁用过去的日期在日期选择器控制。这种控制在打开的对话​​框中,在那里我想禁用过去的日期,以便它抛出错误,如果过去的日期挑选出来的。

I need to disable past dates in datepicker control. This control is opened in a dialog box, there I want to disable past dates so that it throws error if past date is picked.

推荐答案

我想你使用的是 DatePickerDialog 和OnDateSetListener你必须通过给构造不适合您的需求,因为你不得不放弃之前的误差 的日期实际上是设置。

I suppose you are using DatePickerDialog and the OnDateSetListener that you have to pass to the constructor doesn't fit your needs because you have to throw the error before the date is actually set.

在这种情况下,你可以扩展DatePickerDialog,使自己的实施OnDateChanged,这就是所谓每次的日期改变,你会得到作为参数的DatePicker,新的年,月,日的值,这样你就可以检查,如果该日期是过去在这种情况下抛出错误(用面包或其他)和叫DatePicker.updateDate()设置一个正确的值(这样的DatePicker是永诺一致的状态)。

In this case you can extend DatePickerDialog and make your own implementation of OnDateChanged, which is called everytime that the date changes and you get as parameters the DatePicker, and the new year, month and day values, so you can check if that date is past and in that case throw the error (with a Toast or whatever) and call DatePicker.updateDate() to set a correct value (so that DatePicker is allways in a consistent state).

另外,你可以打电话 DatePicker.init(年,monthOfYear,DAYOFMONTH,onDateChangedListener); ,那么你可以通过一个 onDateChangedListener 的实施而无需延长DatePickerDialog

Also, you can call to DatePicker.init(year, monthOfYear, dayOfMonth, onDateChangedListener); then you can pass a onDateChangedListener implementation without having to extend DatePickerDialog