Dismiss DatePickerDialog on pressing back button

后端 未结 8 1946
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-19 12:29

On my view I have a button which when pressed pops up a DatePickerDialog. The poppedup dialog has a \"Done\" button. When I press that button the selected date is populated

8条回答
  •  盖世英雄少女心
    2020-12-19 12:53

    I struggled with this also, but the solution is very simple. The DialogFragment implements the DialogInterface.OnCancelListener and DialogInterface.OnDismissListener and because DialogInterface.OnCancelListener.onCancel gets called before DialogInterface.OnDismissListener.onDismiss, you can clear the date values in onCancel and call the TransactionActivity.populateSetDate method in onDismiss only if the date values are not 0.

    As an aside: to make the Fragment more standalone, it's good practice that the Fragment defines a public interface that the calling activity must implement, so you can call the populateSetDate method on the interface instead of the activity.

    See your code below for implementation of the onCancel and onDismiss:

    public class SelectDateFragment extends DialogFragment
      implements DatePickerDialog.OnDateSetListener
    {
    
      private int year;
      private int month;
      private int day;
    
      @Override
      public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar calendar = Calendar.getInstance();
        int yy = calendar.get(Calendar.YEAR);
        int mm = calendar.get(Calendar.MONTH);
        int dd = calendar.get(Calendar.DAY_OF_MONTH);
        return new DatePickerDialog(getActivity(), this, yy, mm, dd);
      }
    
      public void onDateSet(DatePicker view, int yy, int mm, int dd) {
        // Calls a method on the activity which invokes this fragment
        // ((TransactionActivity)getActivity()).populateSetDate(yy, mm+1, dd); 
        year = yy;
        month = mm;
        day = dd;
      }
    
      // Gets called before onDismiss, so we can erase the selectedDate
      @Override
      public void onCancel(DialogInterface dialog) {
        year = 0;
        month = 0;
        day = 0;
      }
    
    
      @Override
      public void onDismiss(DialogInterface dialog) {
        if (year != 0) {
          ((TransactionActivity)getActivity()).populateSetDate(year, month + 1, day);
        }
      }
    }
    

提交回复
热议问题