Android DatePicker Date Limiting

∥☆過路亽.° 提交于 2019-11-27 16:37:20

问题


I am using DatePicket in my activity ,

I want to limit the date picked by user to todays date.

They should not able to select date greater than todays date.

thank you.


回答1:


yes you can do it very easely the validation here is the exemple:

if(dateObj1.before(dateObj2) || dateObj1.equals(dateObj2)){
//the program runs normally
}
else{
                new AlertDialog.Builder(PM_Edit.this)

                .setTitle("Wrong Data Input!")

                .setMessage("The end Date must be Before the start Date, please insert new Date values")

                .setNeutralButton("Ok",

                new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog,

                int which) {

                }

                }).show();
            }

Credits to: http://www.brighthub.com/mobile/google-android/articles/41545.aspx




回答2:


DatePicker datePicker = (DatePicker)findViewById(R.id.new_date_picker);


datePicker.init(year, month, day, new OnDateChangedListener() {

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

        if(isDateAfter(view)){
            Calendar mCalendar = Calendar.getInstance();
            view.init(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), this);
        }
    }


    private boolean isDateAfter(DatePicker tempView) {
        Calendar mCalendar = Calendar.getInstance();
        Calendar tempCalendar = Calendar.getInstance();
        tempCalendar.set(tempView.getYear(), tempView.getMonth(), tempView.getDayOfMonth(), 0, 0, 0);
        if(tempCalendar.after(mCalendar))
            return true;
        else 
            return false;
    }
});



回答3:


I haven't worked with DatePicker but The documentation doesn't show any methods which can restrict the maximum date the Picker displays, still you can always check for the date it returns and can notify the user about validation criterion.




回答4:


I agree with Sheikh.

Maybe consider doing validation on the entered date and if invalid, notify the user and launch the DatePicker again.

Other than that, maybe a custom widget, but I haven't seen a default way to do this.



来源:https://stackoverflow.com/questions/4943486/android-datepicker-date-limiting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!