简体   繁体   中英

Set DatePicker DialogFragment to specific date

I have the following Date Picker dialog fragment which works just fine and sets the date in the edittext to the date selected in the date picker. What I need to do is set the date in the date picker to the date in the edittext if the edittext is not empty. My dialog fragment is:

public class DatePickerFragment : Android.Support.V4.App.DialogFragment, DatePickerDialog.IOnDateSetListener
{
    // TAG can be any string of your choice.
    public static readonly string TAG = "X:" + typeof(DatePickerFragment).Name.ToUpper();

    // Initialize this value to prevent NullReferenceExceptions.
    Action<DateTime> _dateSelectedHandler = delegate { };

    public static DatePickerFragment NewInstance(Action<DateTime> onDateSelected)
    {
        DatePickerFragment frag = new DatePickerFragment();
        frag._dateSelectedHandler = onDateSelected;
        return frag;
    }

    public override Dialog OnCreateDialog(Bundle savedInstanceState)
    {
        DateTime currently = DateTime.Now;
        DatePickerDialog dialog = new DatePickerDialog(Activity,
                                                       this,
                                                       currently.Year,
                                                       currently.Month - 1,
                                                       currently.Day);

        return dialog;
    }

    public void OnDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
    {
        // Note: monthOfYear is a value between 0 and 11, not 1 and 12!
        DateTime selectedDate = new DateTime(year, monthOfYear + 1, dayOfMonth);
        Log.Debug(TAG, selectedDate.ToLongDateString());
        _dateSelectedHandler(selectedDate);
    }
}

I call the fragment on the click of the edit text, that code is:

        dob.Click += (sender, e) =>
        {
            DatePickerFragment frag = DatePickerFragment.NewInstance(delegate (DateTime time)
            {
                string thedate = time.ToShortDateString();
                if (Utils.Mid(thedate,2,1) == "/")
                {
                    thedate = "0" + thedate;
                }
                dob.Text = thedate;
            });
            frag.Show(SupportFragmentManager, DatePickerFragment.TAG);
        };

I've tried several methods that I've seen on stackoverflow and as yet nothing has worked.

I figured it out. Pretty simple actually. To pass data to a fragment you use a bundle. I changed the call to the fragment to add a bundle containing the initial date like so:

        dob.Click += (sender, e) =>
        {
            Bundle bundlee = new Bundle();
            bundlee.PutString("initDate", dob.Text);
            DatePickerFragment frag = DatePickerFragment.NewInstance(delegate (DateTime time)
            {
                string thedate = time.ToShortDateString();
                if (Utils.Mid(thedate,2,1) == "/")
                {
                    thedate = "0" + thedate;
                }
                dob.Text = thedate;
            });
            frag.Arguments = bundlee;
            frag.Show(SupportFragmentManager, DatePickerFragment.TAG);
        };

Then in the OnCreateDialog method of the fragment I get the data from the bundle and set the initial date of the date picker, like so:

    public override Dialog OnCreateDialog(Bundle savedInstanceState)
    {
        Bundle bundlee = this.Arguments;
        int month = DateTime.Now.Month;
        int day = DateTime.Now.Day;
        int year = DateTime.Now.Year;
        string initDate = bundlee.GetString("initDate");
        if (initDate != "" && initDate != null)
        {
            month = Convert.ToInt32(Utils.Mid(initDate, 1, 2));
            day = Convert.ToInt32(Utils.Mid(initDate, 4, 2));
            year = Convert.ToInt32(Utils.Mid(initDate, 7, 4));

        }

        //DateTime currently = DateTime.Now;
        DatePickerDialog dialog = new DatePickerDialog(Activity,
                                                       this,
                                                       year,
                                                       month - 1,
                                                       day);

        return dialog;
    }

Being a lifelong VB programmer starting with VB4, I just couldn't do without the Mid function, so I created an equivalent in c# and put it in my Utils class (in case you're wondering where that comes from):

class Utils
{
     public static string Mid(string input, int index, char newChar)

    {

        if (input == null)

        {

            throw new ArgumentNullException("input");

        }

        char[] chars = input.ToCharArray();

        chars[index - 1] = newChar;

        return new string(chars);

    }
    public static string Mid(string s, int a, int b)

    {

        string temp = s.Substring(a - 1, b);

        return temp;

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM