Foggy day

Android(Java) - DatePickerDialog 본문

Android

Android(Java) - DatePickerDialog

jinhan38 2021. 1. 8. 13:42

It is a sample code of DatePickerDialog.

 

Here, you can limit maxDate, minDate and implement spinner DatePickerDialog. Also you can remove the specific type in datepickerdialog.

 

 

  private void setDatePicker() {
        b.tvTitleDate.setOnClickListener(view -> {
            Calendar c = Calendar.getInstance();

            DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(),
                    android.R.style.Theme_Holo_Light_Dialog_MinWidth, listener,
                    c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));

            datePickerDialog.getDatePicker().setCalendarViewShown(false);
            datePickerDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
            datePickerDialog.show();

            Calendar minDate = Calendar.getInstance();
            Calendar maxDate = Calendar.getInstance();

            minDate.setTime(2021, 2, 1);
            maxDate.setTime(2030, 12, 31);
            datePickerDialog.getDatePicker().setMinDate(minDate.getTime().getTime());
            datePickerDialog.getDatePicker().setMaxDate(maxDate.getTime().getTime());

            if (currentStateType == state.MONTH) {
                datePickerDialog.getDatePicker().findViewById(Resources.getSystem().getIdentifier("year", "id", "android")).setVisibility(View.VISIBLE);
                datePickerDialog.getDatePicker().findViewById(Resources.getSystem().getIdentifier("month", "id", "android")).setVisibility(View.VISIBLE);
                datePickerDialog.getDatePicker().findViewById(Resources.getSystem().getIdentifier("day", "id", "android")).setVisibility(View.GONE);
            } else if (currentStateType == state.YEAR) {
                datePickerDialog.getDatePicker().findViewById(Resources.getSystem().getIdentifier("year", "id", "android")).setVisibility(View.VISIBLE);
                datePickerDialog.getDatePicker().findViewById(Resources.getSystem().getIdentifier("month", "id", "android")).setVisibility(View.GONE);
                datePickerDialog.getDatePicker().findViewById(Resources.getSystem().getIdentifier("day", "id", "android")).setVisibility(View.GONE);
            }

        });

    }

    private DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(android.widget.DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            Toast.makeText(getContext(), year + "-" + (monthOfYear + 1) + "-" + dayOfMonth + "-", Toast.LENGTH_SHORT).show();
        }
    };