Search code examples
androidandroid-dialogfragment

ANDROID - setOnDismissListener on a DialogFragment


I've got a DialogFragment used to display a TimePickerDialog when pressing a button, and I would like to change the text of the button to the new time set.

My problem is I can't call setOnDismissListener on the DialogFragment from my Activity.

This is my DialogDragment

 public class TimePickerFragment extends DialogFragment
        implements TimePickerDialog.OnTimeSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        int hour = Application.getSettings().getInt("hour", 11);
        int minute = Application.getSettings().getInt("minute", 11);

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        FirstTimeLaunchSettingsActivity.hours = hourOfDay;
        FirstTimeLaunchSettingsActivity.minutes = minute;

    }
}

And this is how I call this DialogFragment

    public void showTimePickerDialog(View v) {
    DialogFragment newFragment = new TimePickerFragment();
    newFragment.show(this.getFragmentManager(), "timePicker");
}

I've already thought making a Handler in my activity which would refresh the Activity every seconde, but that's not how I would like to solve the problem.

I just want, when I close my DialogFragment, my button to be set to the time I've entered.

Thanks for your help.


Solution

  • You can override the onDismiss(DialogInterface dialog) method, which will be called when the DialogFragment is dismissed. You can also do it from your activity with an inline override:

    public void showTimePickerDialog(View v) {
        DialogFragment newFragment = new TimePickerFragment() {
            @Override
            public void onDismiss(DialogInterface dialog){
                // Add your code here
            }
        };
        newFragment.show(this.getFragmentManager(), "timePicker");
    }