How to show Cancel button on DatePicker?

1.2k views Asked by At

I'm using a DialogFragment that displays a DatePicker. How can I show the 'Cancel' button on the dialog?

2

There are 2 answers

0
Sanket Shah On

Try this code as i found from THIS


DatePickerDialog dialog = new DatePickerDialog(this,
              mDateSetListener,
              year, month, day);

  dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.cancel), new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
       if (which == DialogInterface.BUTTON_NEGATIVE) {
          // Do Stuff
       }
    }
  });
0
Vid On

Use this code and modify UI as per your convenient.

/**
     * Prepares & shows the Dialog for selecting date.
     */
    private void prepareDateDialog()
    {
        final Dialog dialog = new Dialog(this, android.R.style.Theme_Holo_Light_Dialog_NoActionBar);
        dialog.setContentView(R.layout.dialog_date_picker);
        datePicker = (DatePicker) dialog.findViewById(R.id.dialog_date_picker_date);

        // initialize DatePicker with the previously initialized values.
        datePicker.init(year, month - 1, dayOfMonth, null);
        TextView tvDone = (TextView) dialog.findViewById(R.id.dialog_date_picker_tv_done);
        TextView tvCancel = (TextView) dialog.findViewById(R.id.dialog_date_picker_tv_cancel);
        tvCancel.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                dialog.dismiss();
            }
        });

        tvDone.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                dialog.dismiss();
                setDate();
            }
        });
        dialog.show();
    }

setDate method..

/**
     * Sets the date selected by the user.
     */
    private void setDate()
    {
        dayOfMonth = datePicker.getDayOfMonth();
        month = (datePicker.getMonth()) + 1;
        year = datePicker.getYear();

        Calendar c = Calendar.getInstance();
        c.set(Calendar.DATE, dayOfMonth);
        c.set(Calendar.MONTH, month);
        c.set(Calendar.YEAR, year);

        String monthCount = "" + month;
        String day = dayOfMonth + "";
        if (dayOfMonth < 9)
            day = "0" + dayOfMonth;
        if (month < 9)
            monthCount = "0" + month;

        selectedDate = day + "-" + monthCount + "-" + year;
        tvDate.setText(selectedDate);
        tvBirthday.setText(selectedDate);
    }