Select A Date in a Fragment

PDF for offline use
Sample Code:
Related Articles:
Related SDKs:

Let us know how you feel about this

Translation Quality


0/250

This recipe will show how to use a DatePickerDialog inside of a Fragment.

Recipe

Follow these steps to use a DatePickerDialog inside a Fragment:

  1. Create a Fragment in your Xamarin.Android project, and have the Fragment implement Android.App.DatePickerDialog.IOnDateSetListener.
  2. Implement the method required by the interface:
public void OnDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
    var date = new DateTime(year, monthOfYear + 1, dayOfMonth);
    View.FindViewById<TextView>(Resource.Id.display_date_text).Text = "You picked " + date.ToString("yyyy-MMM-dd");
}
  1. Create a new class that inherits from DialogFragment:
public class DatePickerDialogFragment : DialogFragment
{
    private readonly Context _context;
    private  DateTime _date;
    private readonly Android.App.DatePickerDialog.IOnDateSetListener _listener;

    public DatePickerDialogFragment(Context context, DateTime date, Android.App.DatePickerDialog.IOnDateSetListener listener  )
    {
        _context = context;
        _date = date;
        _listener = listener;
    }

    public override Dialog OnCreateDialog(Bundle savedState)
    {
        var dialog = new Android.App.DatePickerDialog(_context, _listener, _date.Year, _date.Month - 1, _date.Day);
        return dialog;
    }
}
  1. In the Fragment that was created in step one, modify it so that it will use the DialogFragment subclass:
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    var view = inflater.Inflate(Resource.Layout.fragment_layout, container, false);
    view.FindViewById<Button>(Resource.Id.pick_date_button).Click += (sender, args) =>
                                                                         {
                                                                             var dialog = new DatePickerDialogFragment(Activity, DateTime.Now, this);
                                                                             dialog.Show(FragmentManager, null);
                                                                         };
    return view;
}

Additional Information

The DialogFragment in Android displays a dialog onto of the Activity that is hosting the fragment. This example uses the DialogFragment class around the standard DatePickerDialog. By having the Fragment implement Android.App.DatePickerDialog.IOnDateSetListener it can provide a callback to the DatePickerDialog to respond to when a date is selected.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.