在 Android 中设置 DatePickerDialog 的限制?

Posted

技术标签:

【中文标题】在 Android 中设置 DatePickerDialog 的限制?【英文标题】:Set Limit on the DatePickerDialog in Android? 【发布时间】:2013-08-18 19:12:48 【问题描述】:

如何限制 DatePickerDialog 选择过去 2-12 年或当前日期 0-2 年的日期?

我在活动中有 DatePickerDialog,用于获取儿童和婴儿的出生日期。儿童年龄为(2-12 岁),婴儿年龄为(0-2 岁)。如果我通过 1,那么年龄限制应该是(2-12 岁),如果我通过 2,年龄限制应该是(0-2 岁)。

我可以做些什么来在我的日历中获得这个功能?

我的日历代码是:

date = new DatePickerDialog.OnDateSetListener() 

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                    int dayOfMonth) 
                // TODO Auto-generated method stub
                myCalendar.set(Calendar.YEAR, year);
                myCalendar.set(Calendar.MONTH, monthOfYear);
                myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                String myFormat = "dd/MM/yy"; //In which you need put here
                SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
                dateofBirth.setText(sdf.format(myCalendar.getTime()));
            
        ;

dateofBirth.setOnClickListener(new OnClickListener() 

            @Override
            public void onClick(View v) 
                // TODO Auto-generated method stub
                showDialog(DATE_DIALOG_ID);

            
        );

public Dialog onCreateDialog(int id) 
    final Calendar now = Calendar.getInstance();

    switch (id) 
    case DATE_DIALOG_ID:
        // set date picker as current date
        DatePickerDialog _date =   new DatePickerDialog(this, date,myCalendar
                .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                myCalendar.get(Calendar.DAY_OF_MONTH))
            @Override

            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)   

                if (year > now.get(Calendar.YEAR))

                    view.updateDate(myCalendar
                            .get(Calendar.YEAR), myCalendar
                            .get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));

                if (monthOfYear > now.get(Calendar.MONTH) && year == now.get(Calendar.YEAR))
                    view.updateDate(myCalendar
                            .get(Calendar.YEAR), myCalendar
                            .get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));

                if (dayOfMonth > now.get(Calendar.DAY_OF_MONTH) && year == now.get(Calendar.YEAR) && 
                        monthOfYear == now.get(Calendar.MONTH))
                    view.updateDate(myCalendar
                            .get(Calendar.YEAR), myCalendar
                            .get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));
            

        ;

        return _date;
    
    return null;

【问题讨论】:

【参考方案1】:

所有其他答案似乎都相当复杂,所以我只想说明显而易见的:您可以从DatePickerDialog 获取底层DatePicker(只需调用getDatePicker())并使用以下方法设置其界限:

setMinDate(long minDate) setMaxDate(long maxDate)

其中参数是自默认时区 1970 年 1 月 1 日 00:00:00 以来的通常毫秒数。当然,您仍然需要计算这些值,但这对于 Calendar 类应该是微不足道的:只需获取当前日期并添加或减去 x 年。

细心的读者会注意到,上述设置器直到 API 级别 11 才可用。如果您只针对该(或更新的)平台,那么您就可以开始了。如果您还想支持 Gingerbread 设备(android 2.3 / API 级别 9+),您可以改用 backported version of DatePicker

【讨论】:

那个项目在过去可以救我几天。很高兴知道! 这就是这样做的方法:***.com/questions/13661788/… 我不清楚偏移量可能是负数,我可以在 1970 年之前获得数年。【参考方案2】:

为 DatePickerDialog 设置最小和最大日期是不够的。用户可以点击年份并在年份之间滚动。

您还应该像这样在 DatePicker 上设置年份范围:

datePicker.setYearRange(calendar.get(Calendar.YEAR), calendar.get(Calendar.YEAR) + 1);

【讨论】:

【参考方案3】:

我无法为您提供工作代码,因为我正在旅行并且无法访问我的 PC。但我可以给你一个方法来实现你的目标(或者我认为)。

我不确定这是否会完美运行,但任何方式都值得一试。

请尝试此代码并通知我。

“DatepickerType”是该类的一个整数公共成员变量。

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() 

    // when dialog box is closed, below method will be called.
    public void onDateSet(DatePicker view, int selectedYear,
            int selectedMonth, int selectedDay) 
        int y = Calendar.getInstance().get(Calendar.YEAR);
        switch(DatepickerType)
        case 1:
            if(selectedYear>(y-2))
                //Add message if you want
                selectedYear = y-2;
            
                else if(selectedYear<(y-12)) 
                //Add msg if u want
                    selectedYear = y-12;
            

        case 2:
            if(selectedYear>(y))
                //Add message if you want
                selectedYear = y;
            
                else if(selectedYear<(y-2)) 
                //Add msg if u want
                    selectedYear = y-2;
            
        

        String year1 = String.valueOf(selectedYear);
        String month1 = String.valueOf(selectedMonth+1);
        String day1 = String.valueOf(selectedDay);
        //do what you need
        setLastStatus();

    
;

【讨论】:

【参考方案4】:
    datePickerDialog = new CustomDatePickerDialog(this,
                new OnDateSetListener() 
                    @Override
                    public void onDateSet(DatePicker view, int year,
                            int monthOfYear, int dayOfMonth) 
                        // TODO Auto-generated method stub
                        try 
                            Log.i("DAta SEt", "data set");
                         catch (Exception e) 

                        

                    

                , minYear, minMonth, minDay, maxYear, maxMonth, maxDay);

CustomDatePickerDialog:

public class CustomDatePickerDialog extends DatePickerDialog 

private boolean mIgnoreEvent = false, mignorsunday = true;

public static int mYear, mMonth, mDate, maxYear, maxMonth, maxDay, minYear,
        minMonth, minDay;
public static int dateflag = 0;
public static int dateflag2 = 0;

public CustomDatePickerDialog(Context context, OnDateSetListener callBack,
        int year, int monthOfYear, int dayOfMonth, int maxYear,
        int maxMonth, int maxDay) 
    super(context, callBack, year, monthOfYear, dayOfMonth);
    // TODO Auto-generated constructor stub
    dateflag = 0;
    dateflag2 = 1;
    mYear = year;
    mMonth = monthOfYear;
    mDate = dayOfMonth;

    Log.i("Hello World ::", "Please Its Updating At Every time");

    this.maxYear = maxYear;
    this.maxMonth = maxMonth;
    this.maxDay = maxDay;
    this.minYear = year;
    this.minMonth = monthOfYear;
    this.minDay = dayOfMonth;

    // setTitle("בחרו מתי נח לכם שנתקשר");
    setTitle("We Call U...בחרו מתי נוח לכם ש");



@Override
public void onDateChanged(DatePicker view, int year, int month, int day) 
    // TODO Auto-generated method stub
    super.onDateChanged(view, year, month, day);
    dateflag = 1;
    dateflag2 = 1;
    if (!mIgnoreEvent) 
        mIgnoreEvent = true;
        if (year > maxYear || month > maxMonth && year == maxYear
                || day > maxDay && year == maxYear && month == maxMonth) 
            mYear = maxYear;
            mMonth = maxMonth;
            mDate = maxDay;
            view.updateDate(maxYear, maxMonth, maxDay);
         else if (year < minYear || month < minMonth && year == minYear
                || day < minDay && year == minYear && month == minMonth) 
            mYear = minYear;
            mMonth = minMonth;
            mDate = minDay;
            view.updateDate(minYear, minMonth, minDay);
         else 
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.YEAR, year);
            cal.set(Calendar.MONTH, month);
            cal.set(Calendar.DATE, day);
            if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) 

                if (mignorsunday) 
                    cal.add(Calendar.DATE, 1);
                    mYear = cal.get(Calendar.YEAR);
                    mMonth = cal.get(Calendar.MONTH);
                    mDate = cal.get(Calendar.DATE);
                    mignorsunday = false;
                 else if (!mignorsunday) 
                    mignorsunday = true;
                    cal.add(Calendar.DATE, -1);
                    mYear = cal.get(Calendar.YEAR);
                    mMonth = cal.get(Calendar.MONTH);
                    mDate = cal.get(Calendar.DATE);
                
             else 
                mYear = year;
                mMonth = month;
                mDate = day;
            
            view.updateDate(mYear, mMonth, mDate);
        
        setTitle("We Call U...בחרו מתי נוח לכם ש");
        mIgnoreEvent = false;
    


public int getSelectedYear() 
    return mYear;


public int getSelectedMonth() 
    return mMonth;


public int getSelectedDate() 
    return mDate;


【讨论】:

【参考方案5】:

这是工作代码,您必须根据您的代码进行一些更改。就像您可以添加儿童和婴儿的最小和最大年龄一样。

private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() 

    public void onDateSet(DatePicker view, int year, int monthOfYear,
                          int dayOfMonth) 
    /*
     * mYear = year;
     * mMonth = monthOfYear;
     * mDay = dayOfMonth;
     */
        if (year > maxYear || monthOfYear > maxMonth && year == maxYear ||
                dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth) 
            view.updateDate(maxYear, maxMonth, maxDay);
            //you can add toast message here for max year selection
         else if (year < minYear || monthOfYear < minMonth && year == minYear ||
                dayOfMonth < minDay && year == minYear && monthOfYear == minMonth) 
            view.updateDate(minYear, minMonth, minDay);
            //you can add toast message here for min year selection
         else 
            view.updateDate(year, monthOfYear, dayOfMonth);
        
    

;

@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mPickDate = (Button) findViewById(R.id.pickDate);
    mPickDate.setOnClickListener(this);

    final Calendar c = Calendar.getInstance();
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);

    maxYear = mYear - 2;//make a proper condition to change it the based on the   child/infant
    maxMonth = mMonth;
    maxDay = mDay;

    minYear = mYear - 12;//make a proper condition to change it the based on the child/infant
    minMonth = mMonth;
    minDay = mDay;



@Override
public void onClick(View v) 
    showDialog(DATE_DIALOG_ID);


@Override
protected Dialog onCreateDialog(int id) 
    switch (id) 
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this, mDateSetListener, mYear - minYear,
                    mMonth, mDay);
    
    return null;

【讨论】:

我还在更新等待 @Gauravnow my ans is complete .. 添加条件以在 oncreate() 中根据 child 和 infant 更改 maxyear 和 minyear 在按钮上单击日历未打开。我必须在已发布的代码中进行哪些更改 @Gauravyou 必须在选择日期选择器之前根据孩子/婴儿设置 maxyear 和 minyear。如果选择了 childRadiobutton,则需要一个单选按钮来设置这些值设置范围为 2-12 否则为 0-2 .dynamically,一旦您进入日期选择器对话框,就不可能更改范围。这应该在打开对话框之前完成 你能帮我编辑我的代码吗,因为我试过你说的,但我做不到【参考方案6】:

希望对您有所帮助。最好使用对话框片段,因为不推荐使用对话框的showDialog()。 另请注意,它仅适用于高于 11 的 API。因此,请将清单中的 min.sdk 更改为 11。

Calendar calendar=Calendar.getInstance();
    int mDay = calendar.get(Calendar.DAY_OF_MONTH), mMonth = calendar.get(Calendar.MONTH), mYear = calendar.get(Calendar.YEAR);


    int minDay = calendar.get(Calendar.DAY_OF_MONTH), minMonth = calendar.get(Calendar.MONTH), minYear = calendar.get(Calendar.YEAR)-12;

int maxDay = calendar.get(Calendar.DAY_OF_MONTH), maxMonth = calendar.get(Calendar.MONTH), maxYear = calendar.get(Calendar.YEAR)-12;


public void onDate(View view) 
        System.out.println("hello");
        DialogFragment fragment = new SelectDateFragment();
        fragment.show(getFragmentManager(), "Date Picker");
    

    class SelectDateFragment extends DialogFragment implements
            DatePickerDialog.OnDateSetListener 

        public Dialog onCreateDialog(Bundle savedInstanceState) 


            System.out.println("entrering on create dialog");;

            return new DatePickerDialog(getActivity(), this, mYear, mMonth,
                    mDay) 

                public void onDateChanged(DatePicker view, int year,
                        int monthOfYear, int dayOfMonth) 
                    System.out.println("----------onDateChanged()-----------"
                            + year + "--" + year);
                    System.out.println("----------onDateChanged()-----------"
                            + monthOfYear + "--" + monthOfYear);
                    System.out.println("----------onDateChanged()-----------"
                            + dayOfMonth + "--" + dayOfMonth);

                    if ((minYear < year)
                            || ((minMonth < monthOfYear) && (minYear == year))
                            || ((minDay < dayOfMonth) && (minYear == year) && (minMonth == monthOfYear))) 
                        view.updateDate(minYear, minMonth - 1, minDay);

                    

if ((maxYear > year)
                            || ((maxMonth > monthOfYear) && (maxYear == year))
                            || ((maxDay > dayOfMonth) && (maxYear == year) && (maxMonth == monthOfYear))) 
                        view.updateDate(maxYear, maxMonth - 1, maxDay);

                    

                
            ;

        

        @Override
        public void onDateSet(android.widget.DatePicker view, int year,
                int monthOfYear, int dayOfMonth) 
            System.out.println("year=" + year + "day=" + dayOfMonth + "month="
                    + monthOfYear);
            mYear=year;
            mMonth=monthOfYear;
            mDay=dayOfMonth;

            onPopulateSet(year, monthOfYear + 1, dayOfMonth);

        


        private void onPopulateSet(int year, int i, int dayOfMonth) 
            EditText et_setDate;
            et_setDate = (EditText) findViewById(R.id.register_et_dob);
            et_setDate.setText(dayOfMonth + "/" + i + "/" + year);
            System.out.println("enetring on populate Set");

        

    

【讨论】:

【参考方案7】:
val cal = Calendar.getInstance()
            todayDay = cal.get(Calendar.DAY_OF_MONTH)
            todayMonth = cal.get(Calendar.MONTH)
            todayYear = cal.get(Calendar.YEAR)
            todayHour = cal.get(Calendar.HOUR)
            todayMin = cal.get(Calendar.MINUTE)


            val dpd = DatePickerDialog(this, DatePickerDialog.OnDateSetListener  it, selectedYear, selectedMonth, selectedDay ->
                dateDisplay.isVisible = true
                val selectedDate = "$selectedDay/$selectedMonth + 1/$selectedYear"
                //Implementing SimpleDateFormat
                val sdf = SimpleDateFormat("dd/mm/yyyy", Locale.ENGLISH)
                val formatedDate = sdf.parse(selectedDate)
                //this variable is of type Date
                val selectedTime = formatedDate!!.time / 60000


                val todayDate = sdf.parse(sdf.format(System.currentTimeMillis()))
                val todayTime = todayDate!!.time / 60000

                dateDisplay.text = formatedDate.toString()
                ageInMins.text = (todayTime - selectedTime).toString()

            , todayYear, todayMonth, todayDay)
            dpd.datePicker.setMaxDate(Date().time - 86400000)
            dpd.datePicker.setBackgroundColor(Color.RED)
            dpd.show()

【讨论】:

以上是关于在 Android 中设置 DatePickerDialog 的限制?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Android 应用中设置全息黑暗主题?

Android:如何在 android constraintLayout 中设置视图的最大宽度?

Android:如何在 android constraintLayout 中设置视图的最大宽度?

如何在 Android 中设置 AlertDialog 的大小? [复制]

如何使用 Ionic\Cordova 在 android 中设置图标和启动画面

在 Android 应用程序中设置初始焦点