如何使用DatePicker设置最小和最大日期,例如用户无法将日期设置为当前日期。同样,用户将无法在1960年之前选择日期,到目前为止,我已经能够设置DatePicker,我的代码如下:
public class MainActivity extends FragmentActivity {
EditText mEdit;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void selectDate(View view) {
DialogFragment newFragment = new SelectDateFragment();
newFragment.show(getSupportFragmentManager(), "DatePicker");
}
public void populateSetDate(int year, int month, int day) {
mEdit = (EditText)findViewById(R.id.editText1);
mEdit.setText(month+"/"+day+"/"+year);
}
public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}
public void onDateSet(DatePicker view, int yy, int mm, int dd) {
populateSetDate(yy, mm+1, dd);
}
}
}
答案 0 :(得分:0)
在 DatePickerDialog 中,有两种设置 min 和最大日期的方法,输入时间为<强>毫秒强>
所以代码就像
DatePickerDialog d = new DatePickerDialog(getActivity(), this, yy, mm, dd);
DatePicker dp = d.getDatePicker();
dp.setMaxDate(maxDate);
dp.setMinDate(minDate);
return d;
但是此方法可在 API Level 11 中使用。
答案 1 :(得分:0)
您可以尝试以下内容。
public class DatePickerDialogWithMaxMinRange extends DatePickerDialog {
static int maxYear=2014; // max date which you want to set
static int maxMonth=11;
static int maxDay=31;
int minYear=1960; // min date which you want to set
int minMonth=0;
int minDay=1;
public DatePickerDialogWithMaxMinRange(Context context, OnDateSetListener callBack,int minYear,int minMonth,int minDay,int maxYear,int maxMonth,int maxDay) {
super(context,callBack, maxYear, maxMonth, maxDay);
this.minDay = minDay;
this.minMonth = minMonth;
this.minYear = minYear;
DatePickerDialogWithMaxMinRange.maxDay = maxDay;
DatePickerDialogWithMaxMinRange.maxMonth = maxMonth;
DatePickerDialogWithMaxMinRange.maxYear = maxYear;
}
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
super.onDateChanged(view, year, monthOfYear, dayOfMonth);
if (year > maxYear ||monthOfYear > maxMonth && year == maxYear||
dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth){
view.updateDate(maxYear, maxMonth, maxDay);
}else if(year < minYear ||monthOfYear < minMonth && year == minYear||
dayOfMonth < minDay && year == minYear && monthOfYear == minMonth){
view.updateDate(minYear, minMonth, minDay );
}
}
}