Search code examples
androidxamarintimepickerandroid-timepickertimepickerdialog

Timepicker with DialogFragment xamarin android


I am opening timepicker in dialogfragment in my fragment class.

var dialog = new TimePickerDialogFragment(_activity, DateTime.Now, new OnTimeSetListener());

                    dialog.Cancelable = false;
                    dialog.Show(_fg, null);

Here TimePickerDialogFragment extends DialogFragment.

public class TimePickerDialogFragment : DialogFragment    
{        
private Activity _activity;

private DateTime _date;


private readonly TimePickerDialog.IOnTimeSetListener _listener;

        public TimePickerDialogFragment(Activity activity, DateTime date, TimePickerDialog.IOnTimeSetListener listener)
        {
            _activity = activity;
            _date = date;
            _listener = listener;
        }

        public override Dialog OnCreateDialog(Bundle savedState)
    {
        var dialog = new TimePickerDialog(_activity, _listener, _date.Hour, _date.Minute, true);
        dialog.SetTitle("Enter Time"+ DateTime.Now.ToString());
        return dialog;
    }
    }

Here is my listener class

public class OnTimeSetListener : Java.Lang.Object, TimePickerDialog.IOnTimeSetListener 

    {
      public void OnTimeSet(TimePicker view, int hourOfDay, int minute)
      {

      }
    }

Now I want to update the title as soon as user selects a new time while the pop up is opened. The OnTimeSet is called when I click on set button on popup.I don't want to update there. How can I achieve this? Is there any other way to open timepicker dialog apart from this that I can try? I am new to android. Any help is appreciated.


Solution

  • In order to get notified when time is changed you need to create a subclass of TimePickerDialog and override OnTimeChanged method which is called when user changes time in the picker. Add a TimeChanged event in the new subclass and trigger it from the overridden method. In the event handler you will be able to set the dialog title based on the new time.