Home » Android » Android Applications » Selecting Birthdate using Material Calendar in Android

Selecting Birthdate using Material Calendar in Android

In this post, we will show you how to use Calendar from Material components for selecting Birthdate of user during registration process in UI.

try {

    final Calendar c = Calendar.getInstance();
    currentYear = c.get(Calendar.YEAR);

    MaterialDatePicker.Builder materialDateBuilder = MaterialDatePicker.Builder.datePicker();
    materialDateBuilder.setInputMode(MaterialDatePicker.INPUT_MODE_CALENDAR); //set input mode
    materialDateBuilder.setTitleText("Select your Birthdate");

    CalendarConstraints.Builder constraintsBuilder = setupConstraintsBuilder(currentYear); //pass current year
    materialDateBuilder.setCalendarConstraints(constraintsBuilder.build());

    final MaterialDatePicker < Long > materialDatePicker = materialDateBuilder.build();

    materialDatePicker.show(getSupportFragmentManager(), "MATERIAL_CALENDER_DATE_PICKER");

    materialDatePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener() {
        @Override
        public void onPositiveButtonClick(Object epochTime) {
            Date date = new Date((Long) epochTime);

            try {
                SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
                edtBirthdate.setText(sdf.format(date));
            } catch (Exception e) {
                e.printStackTrace();
            }

            //birthdate.setText(materialDatePicker.getHeaderText());
        }
    });
} catch (Exception e) {
    e.printStackTrace();
}
private CalendarConstraints.Builder setupConstraintsBuilder(int currentYear) {
    CalendarConstraints.Builder constraintsBuilder = new CalendarConstraints.Builder();
    Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    c.set(1960, 01, 01);
    Calendar c_end = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    c_end.set((currentYear - 18), 01, 01); //dont allow less than 18 year age

    final long DEFAULT_START = c.getTimeInMillis();
    final long DEFAULT_END = c_end.getTimeInMillis();

    constraintsBuilder.setStart(DEFAULT_START);
    constraintsBuilder.setEnd(DEFAULT_END);
    constraintsBuilder.setOpenAt(DEFAULT_END);
    return constraintsBuilder;
}

In Above code below code create the Material Date picker builder.

    MaterialDatePicker.Builder materialDateBuilder = MaterialDatePicker.Builder.datePicker();

Below code sets the Input Mode of Calender, we are using INPUT_MODE_CALENDAR to show the complete calendar.

    materialDateBuilder.setInputMode(MaterialDatePicker.INPUT_MODE_CALENDAR); //set input mode

Set the title which user can see on the opened Calendar

    materialDateBuilder.setTitleText("Select your Birthdate");

Calendar In C Programming With Sour...
Calendar In C Programming With Source Code Free Download | C project with source code

Leave a Comment