0

I have this fragment:

public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

    private DatePickerDialog dpDialog;
    private Listener listener;

    public interface Listener {
        public void getDate(String date);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        listener  = (Listener)getActivity();

        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        dpDialog = new DatePickerDialog(getActivity(), this, year, month, day);
        return dpDialog;
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int day) {
        String dateString = DateFormat.getDateInstance().format(Common.getDateFromDatePicker(view));

        if (listener != null) {
            listener.getDate(dateString);
        }
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        dpDialog.cancel();
        super.onCancel(dialog);
    }
}

Pressing Back still overwrites my date in a TextView.

What is the correct way to handle cancel?

Ivan-Mark Debono
  • 15,500
  • 29
  • 132
  • 263

2 Answers2

0

I have almost the exact same thing in my app, and it works as expected - pressing Back just exits the dialog without filling in the EditText.

The only difference is that I don't override the onCancel. That might be worth a try.

Edit: here's my date picker:

public static class GameDatePicker extends DialogFragment implements OnDateSetListener
{
    /**
     * start with today's date by default
     */
    @Override
    @NonNull
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    /**
     * handle the date being picked
     */
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
    {
        GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
        cal.set(year, monthOfYear, dayOfMonth);

        DateFormat dateFormat = SimpleDateFormat.getDateInstance();
        String formattedDate = dateFormat.format(cal.getTime());

        EditText dateText = (EditText) getActivity().findViewById(R.id.dateText);
        dateText.setText(formattedDate);
    }
}
Marc
  • 106
  • 1
  • 4
0

You should try setOnCancelListener, setOnDismissListener, setCancelledOnTouchOutside(true), or setCancelable(true). All of these methods already described here:

https://stackoverflow.com/a/14790168/3922207

http://developer.android.com/reference/android/app/DialogFragment.html

Community
  • 1
  • 1
Anggrayudi H
  • 14,977
  • 11
  • 54
  • 87