gpt4 book ai didi

android - 使用 DatePickerDialog 阻止用户选择过去的日期

转载 作者:行者123 更新时间:2023-11-29 14:28:30 25 4
gpt4 key购买 nike

This question描述了如何使用 DatePicker 小部件执行此操作,但我没有得到类似的东西。

我有这些:

@Override
protected Dialog onCreateDialog(int id)
{

switch (id)
{
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, mYear1, mMonth1, mDay1);
case DATE_DIALOG_ID_2:
return new DatePickerDialog(this, mDateSetListener2, mYear2, mMonth2, mDay2);
case DATE_DIALOG_ID_3:
return new DatePickerDialog(this, mDateSetListener3, mYear3, mMonth3, mDay3);
}
return null;
}


protected void onPrepareDialog(int id, Dialog dialog)
{

switch (id)
{
case DATE_DIALOG_ID:
((DatePickerDialog) dialog).updateDate(mYear1, mMonth1, mDay1);
break;
case DATE_DIALOG_ID_2:
((DatePickerDialog) dialog).updateDate(mYear2, mMonth2, mDay2);
break;
case DATE_DIALOG_ID_3:
((DatePickerDialog) dialog).updateDate(mYear3, mMonth3, mDay3);
break;
}
}

然后是三个DatePickerDialog.OnDateSetListener()

这些 DatePickerDialogs 上没有 setMax() 或 setMin()。

提前致谢。

最佳答案

只需实现您自己的 DatePickerDialog,如果用户试图将日期更改为低于最小日期,它会将日期更改回允许的日期。

我正在使用的版本是:

public class MyDatePickerDialog extends DatePickerDialog{

private Date maxDate;
private Date minDate;

public MyDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
super(context, callBack, year, monthOfYear, dayOfMonth);
init(year, monthOfYear, dayOfMonth);
}

public MyDatePickerDialog(Context context, int theme, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
super(context, theme, callBack, year, monthOfYear, dayOfMonth);
init(year, monthOfYear, dayOfMonth);
}

private void init(int year, int monthOfYear, int dayOfMonth){
Calendar cal = Calendar.getInstance();

cal.set(1970, Calendar.JANUARY, 1);
minDate = cal.getTime();

cal.set(3000, Calendar.JANUARY, 1);
maxDate = cal.getTime();

cal.set(year, monthOfYear, dayOfMonth);
}

public void onDateChanged (final DatePicker view, int year, int month, int day){
Calendar cal = Calendar.getInstance();
cal.set(year, month, day);
Date currentDate = cal.getTime();

final Calendar resetCal = cal;
if(!minDate.before(currentDate) ){
cal.setTime(minDate);
view.updateDate(resetCal.get(Calendar.YEAR), resetCal.get(Calendar.MONTH), resetCal.get(Calendar.DAY_OF_MONTH));

}else if(maxDate.before(currentDate)){
cal.setTime(maxDate);
view.updateDate(resetCal.get(Calendar.YEAR), resetCal.get(Calendar.MONTH), resetCal.get(Calendar.DAY_OF_MONTH));
}
}

public void setMaxDate(Date date){
this.maxDate = date;
}

public void setMinDate(Date date){
this.minDate = date;
}

关于android - 使用 DatePickerDialog 阻止用户选择过去的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10835788/

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