如何限制DatePicker在特定日期之前显示日期?

时间:2015-02-10 05:43:58

标签: android datepicker

这里我需要限制toDt的datepicker对话框接受fromDt以下的日期。我怎么做?请帮忙。

private void setDateTimeField()
{
    fromDt_edt.setOnClickListener(this);
    toDt_edt.setOnClickListener(this);

    Calendar newCalendar = Calendar.getInstance();
    fromDt = new DatePickerDialog(this, new OnDateSetListener()
    {
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
        {
            Calendar newDate = Calendar.getInstance();
            newDate.set(year, monthOfYear, dayOfMonth);
            fromDt_edt.setText(dateFormatter.format(newDate.getTime()));
        }

    },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));

    toDt = new DatePickerDialog(this, new OnDateSetListener()
    {
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
        {
            Calendar newDate = Calendar.getInstance();
            newDate.set(year, monthOfYear, dayOfMonth);
            toDt_edt.setText(dateFormatter.format(newDate.getTime()));
        }

    },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}

2 个答案:

答案 0 :(得分:1)

public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
        {
            year = year-(requird year); //year you want to restrict 
            monthOfYear = (requird month); // month of your restricted year
            dayOfMonth = (requird day); //day of restricted Month of that year

            Calendar newDate = Calendar.getInstance();
            newDate.set(year, monthOfYear, dayOfMonth);
            fromDt_edt.setText(dateFormatter.format(newDate.getTime()));
        }

答案 1 :(得分:0)

覆盖onDateChanged方法,如下面的代码所示,我的年,月,日是特定日期。

@Override
public void onDateChanged(DatePicker view, int year,int monthOfYear, int dayOfMonth) {
                    c = Calendar.getInstance();
                    myear = c.get(Calendar.YEAR);
                    mmonth = c.get(Calendar.MONTH);
                    mday = c.get(Calendar.DAY_OF_MONTH);

                    if (year < myear)
                        view.updateDate(myear, mmonth, mday);

                    if (monthOfYear < mmonth && year == myear)
                        view.updateDate(myear, mmonth, mday);

                    if (dayOfMonth < mday && year == myear
                            && monthOfYear == mmonth)
                        view.updateDate(myear, mmonth, mday);
}