Android的日期选择最小最大日期API级别前11Android的日期选择最小最大日期API级别前

2019-05-16 19:21发布

我想在Android上的日期选取器的最小和最大日期设置为前API级别11.我用下面的代码:

mDatePickerField = startDatePickerDialog.getClass().getDeclaredField("mDatePicker");
mDatePickerField.setAccessible(true);

DatePicker startDatePickerInstance =(DatePicker)mDatePickerField.get(startDatePickerDialog);
startDatePickerInstance.init(mYearMin, mMonthMin, mDayMin, new DatePicker.OnDateChangedListener() {
    @Override
    public void onDateChanged(DatePicker datePicker, int i, int i1, int i2) {
        Date maxDate = new Date(mYearMax, mMonthMax, mDayMax, 0, 0, 0);
        Date selectedDate = new Date(i, i1, i2, 0, 0, 0);
        if (selectedDate.after(maxDate)) {
            datePicker.updateDate(mYearMax, mMonthMax, mDayMax);                                        
        }
    }
}

然而, updateDate方法火灾onDateChanged一次不更新日期选择器。
任何人都可以帮助解决这个问题?

Answer 1:

您可以设置范围使用init方法日期选择器。 实施例与最小值:

// Calendar
this.calendar = new GregorianCalendar();
this.datePicker = (DatePicker) findViewById(R.id.xxxxx);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    // (picker is a DatePicker)
    this.datePicker.setMinDate(this.calendar.getTimeInMillis());
} else {
    final int minYear = this.calendar.get(Calendar.YEAR);
    final int minMonth = this.calendar.get(Calendar.MONTH);
    final int minDay = this.calendar.get(Calendar.DAY_OF_MONTH);

    this.datePicker.init(minYear, minMonth, minDay,
            new OnDateChangedListener() {

                public void onDateChanged(DatePicker view, int year,
                        int month, int day) {
                    Calendar newDate = Calendar.getInstance();
                    newDate.set(year, month, day);

                    if (calendar.after(newDate)) {
                        view.init(minYear, minMonth, minDay, this);
                    }
                }
            });
    Log.w(TAG, "API Level < 11 so not restricting date range...");
}


Answer 2:

这DatePicker的自定义类允许我们指定Max和敏时间

public class DatePickerDialogWithMaxMinRange extends DatePickerDialog {

 static int maxYear=2005; 
 static int maxMonth=11;
 static int maxDay=31;

 int minYear=1955;
 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 );
            }
}

}

//在Activity类使用此代码或片段指定成员作为

private int intCurrentYear;
private int intCurrentMonth;
private int intCurrentDay;
private int intMaxYear;
private int intMaxMonth;
private int intMaxDay;
private int intMinYear;
private int intMinDay;
private int intMinMonth;

    DatePickerDialogWithMaxMinRange datePickerDialog= null;
DatePickerDialog.OnDateSetListener datePickerOnDateSetListener;
Calendar myCalendar;

//调用的onCreate这个方法或者其它任何ü要..

注意:您需要通过自定义监听器datepickerdialog后日期选择器对话框中选择要更新的日期

public void setDate() {
    /*
     * Initialise Listener for date set
     */

    datePickerOnDateSetListener = new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            edtTxtPlayerBirthDay.setText(new StringBuilder().append(year)
                    .append("-").append(monthOfYear + 1).append("-")
                    .append(dayOfMonth));
        }
    };

    // initialise DatePicker 

    myCalendar = Calendar.getInstance();

    intCurrentYear = myCalendar.get(Calendar.YEAR);
    intCurrentMonth = myCalendar.get(Calendar.MONTH);
    intCurrentDay = myCalendar.get(Calendar.DAY_OF_MONTH);

    intMaxYear =  intCurrentYear - 2000;
    intMaxMonth = intCurrentMonth;
    intMaxDay =  intCurrentDay;

    intMinYear =  intCurrentYear - 1950;
    intMinMonth = intCurrentMonth;
    intMinDay =  intCurrentDay; 

    datePickerDialog = new DatePickerDialogWithMaxMinRange(
            context, datePickerOnDateSetListener,intMinYear,intMinMonth,intMinDay,intMaxYear,intMaxMonth,intMaxDay);
}

当创建日期选择器通过MINDATE和的maxDate按照乌拉圭回合的要求,用于显示当按钮点击或任何其它控制把这段代码里面为onclicklistener日期选择...

datePickerDialog.show();


Answer 3:

发现一个很酷的方式来设置minmax的日期DatePickerDialog 。 适用于所有的Android版本。 只要你需要返回DatePickerDialog基于Android版本

protected Dialog onCreateDialog(int id)
{
    switch ( id )
    {
        case DATE_DIALOG_ID:
            DatePickerDialog dialog = null;
            if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB )
            {
                dialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener()
                {
                    @Override
                    public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDate)
                    {
                        mTextView.setText(selectedDate + "/" + selectedMonth + 1 + "/" + selectedYear);
                    }
                }, year, month - 1, date);
                Calendar currentDate = Calendar.getInstance();
                dialog.getDatePicker().setMaxDate(currentDate.getTimeInMillis());
                //If you need you can set min date too
            }
            else
            {
                dialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener()
                {
                    @Override
                    public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDate)
                    {
                        mTextView.setText(selectedDate + "/" + selectedMonth + 1 + "/" + selectedYear);
                    }
                }, year, month - 1, date)
                {
                    @Override
                    public void onDateChanged(DatePicker view, int year, int month, int day)
                    {
                        if ( year <= maxYear && month + 1 <= maxMonth && date <= maxDate ) //meets your criteria
                        {
                            view.updateDate(year, month, date); //update the date picker to selected date
                        }
                        else
                        {
                            view.updateDate(maxYear, maxMonth - 1, maxDate); // or you update the date picker to previously selected date
                        }
                    }
                };
            }
            return dialog;
    }
    return null;
}


Answer 4:

编辑您DatePicker.java添加以下代码3个摘录。

声明用于限制最小和最大日期的变量。

// Variables for defining minimum date 
private int minimumDay;
private int minimumMonth;
private int minimumYear;

// Variables for defining maximum date 
private int maximumDay;
private int maximumMonth;
private int maximumYear;

构造函数后,您必须重写onDateChanged方法。

// Called every time the user changes DatePicker values
public void onDateChanged(DatePicker view, int year, int monthOfYear, 
        int dayOfMonth) {

    // Test if chosen date is before minimum date
    boolean beforeMinDate = false;
    boolean afterMaxDate = false;

    if(year < minimumYear){
        beforeMinDate = true;
    }
    else if(year == minimumYear){
        if(monthOfYear < minimumMonth){
            beforeMinDate = true;
        }
        else if(monthOfYear == minimumMonth){
            if(dayOfMonth < minimumDay){
                beforeMinDate = true;
            }
        }
    }

    // Test if chosen date is after maximum date
    if(!beforeMinDate){
        if(year > maxYear){
            afterMaxDate = true;
        }
        else if(year == maxYear){
            if(monthOfYear > maxMonth){
                afterMaxDate = true;
            }
            else if(monthOfYear == maxMonth){
                if(dayOfMonth > maxDay){
                    afterMaxDate = true;
                }
            }
        }
    }

    // If chosen date is before minimum date, update the date and internal
    // calendar to minimum date, else, check similarly fot the maximum
    // date, else, use the valid chosen date.
    if(beforeMinDate)
    {
        mCalendar.set(minimumYear, minimumMonth, minimumDay, 
                mCalendar.get(Calendar.HOUR_OF_DAY), 
                mCalendar.get(Calendar.MINUTE));
        updateDate(minimumYear, minimumMonth, minimumDay);
    }
    else if (afterMaxDate)
    {
        mCalendar.set(maximumYear, maximumMonth, maximumDay, 
                mCalendar.get(Calendar.HOUR_OF_DAY), 
                mCalendar.get(Calendar.MINUTE));
        updateDate(maximumYear, maximumMonth, maximumDay);
    }
    else
        mCalendar.set(year, monthOfYear, dayOfMonth, 
                mCalendar.get(Calendar.HOUR_OF_DAY), 
                mCalendar.get(Calendar.MINUTE));
}

而现在,创造的最小和最大日期setter方法。

    // Method to define minimum permitted date for the picker.
    public void setMinimumDate(int minimumDay, int minimumMonth, 
            int minimumYear)
    {
        this.minimumDay = minimumDay;
        this.minimumMonth = minimumMonth;
        this.minimumYear = minimumYear;
    }

    //Method to define maximum permitted date for the picker.
    public void setMaximumDate(int maximumDay, int maximumMonth, 
            int maximumYear)
    {
        this.maximumDay = maximumDay;
        this.maximumMonth = maximumMonth;
        this.maximumYear = maximumYear;
    }

第二部分,您拨打的DatePicker对话的活动中,你需要设置的最小和最大的停留日期。 下面的代码将当前日期作为最小的和未来的最大之日起两年。

    // Define current date as the minimum desired date
    Calendar c = Calendar.getInstance(); 
    int currentDay = c.get(Calendar.DAY_OF_MONTH);
    int currentMonth = c.get(Calendar.MONTH);
    int currentYear = c.get(Calendar.YEAR);
    inicioDateTimePicker.setMinimumDate(currentDay, currentMonth, 
            currentYear);

    // Define two years in the future as the maximum desired date
    Calendar c = Calendar.getInstance(); 
    int currentDay = c.get(Calendar.DAY_OF_MONTH);
    int currentMonth = c.get(Calendar.MONTH);
    int currentYear = c.get(Calendar.YEAR);
    inicioDateTimePicker.setMinimumDate(currentDay, currentMonth, 
            currentYear + 2);


Answer 5:

你不能。 我处理这个问题的方法是通过使用if语句的DatePicker的:

import android.os.Build.*;

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    // (picker is a DatePicker)
    picker.setMinDate(...);
} else {
    Log.w(TAG, "API Level < 11 so not restricting date range...");
}

最后我什么都不做的TimePicker。

有什么好消息?

SimonVT已经向后移植两个的DatePicker和TimePicker,让您可以享受在早期的API级别的最新功能:

  • https://github.com/SimonVT/android-datepicker
  • https://github.com/SimonVT/android-timepicker


Answer 6:

根据@ yostyle的答案,我做了这台为DatePicker的最小和最大日期的方法。 我的DatePicker是一个AlertDialog内部使用的,因为我需要一些额外的自定义,但这种方法可以直接在任何DatePickerDialog或任何自定义的DatePicker的使用:

/**
     * Compat utility method that will set the minimum date and the maximum date for the DatePicker view.
     * <p/>
     * If the current API is greater than 11, than the normal {@link android.widget.DatePicker#setMinDate(long)} and
     * {@link android.widget.DatePicker#setMaxDate(long)} methods will be used.
     * <p/>
     *
     * @param minCalendar
     *         The minimum date for the picker
     * @param maxCalendar
     *         The maximum date for the picker
     */
    private void initDatePickerCompat(final Calendar minCalendar, final Calendar maxCalendar) {
        if (null == mDatePicker) {
            // Exit early if DatePicker view was not initialized
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // (mDatePicker is a DatePicker)
            mDatePicker.setMinDate(minCalendar.getTimeInMillis());
            mDatePicker.setMaxDate(maxCalendar.getTimeInMillis());
        } else {
            final int minYear = minCalendar.get(Calendar.YEAR);
            final int minMonth = minCalendar.get(Calendar.MONTH);
            final int minDay = minCalendar.get(Calendar.DAY_OF_MONTH);

            final int maxYear = maxCalendar.get(Calendar.YEAR);
            final int maxMonth = maxCalendar.get(Calendar.MONTH);
            final int maxDay = maxCalendar.get(Calendar.DAY_OF_MONTH);

            mDatePicker.init(minYear, minMonth, minDay, new DatePicker.OnDateChangedListener() {
                @Override
                public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                    Calendar newCalendar = Calendar.getInstance();
                    newCalendar.set(year, monthOfYear, dayOfMonth);

                    if (newCalendar.after(maxCalendar)) {
                        // MAX
                        view.updateDate(maxYear, maxMonth, maxDay);
                    } else if (newCalendar.before(minCalendar)) {
                        // MIN
                        view.updateDate(minYear, minMonth, minDay);
                    } else {
                        // BETWEEN
                        view.updateDate(year, monthOfYear, dayOfMonth);
                    }
                }
            });
        }
    }

请记住,这个方法应该DatePicker的初始化之后,像这样被称为:

mDatePicker = (DatePicker) view.findViewById(R.id.datePicker);
mDatePicker.init(year, monthOfYear, dayOfMonth, this);
DateTime minDate = new DateTime();
DateTime maxDate = minDate.plusYears(10);
// Set the minimum and the maximum date for the date picker
initDatePickerCompat(minDate.toCalendar(Locale.getDefault()), maxDate.toCalendar(Locale.getDefault()));


Answer 7:

只使用值(最小和最大)谈到从日历设置DatePiker.MaxDate&DatePiker.MinDate尝试像一些事情:

 DatePickerDialog dialog = new DatePickerDialog();

 Java.Util.TimeZone GMT = new SimpleTimeZone(TimeZoneInfo.Local.BaseUtcOffset.Hours, "GMT"); 
 Calendar maxDate = Calendar.GetInstance(GMT);
 maxDate.Set(DateTime.Now.Year, DateTime.Now.Month - 1, DateTime.Now.Day);

 Calendar minDate = Calendar.GetInstance(GMT);
 minDate.Set(DateTime.Now.Year - 2, DateTime.Now.Month - 1, DateTime.Now.Day);

 dialog.DatePicker.MaxDate = maxDate.TimeInMillis;
 dialog.DatePicker.MinDate = minDate.TimeInMillis;


文章来源: Android datepicker min max date before api level 11