Android Time Preference Dialog with Support Library

  • Replies:0
  • OpenNot stickiedUnanswered
  • Forum posts: 26

Aug 11, 2016 10:23:42 AM via Website

I'm confused about using Android Preferences with the Support v7 or v14 library.
It seems like every couple of months Google changes the API.
I'm trying to create a Time Preference Dialog. However, my current one doesn't work with the Support Library.

public class TimePickerPreference : DialogPreference
{
   private int lastHour = 0;
   private int lastMinute = 0;
   private TimePicker picker = null;

public static int GetHour(string time)
{
    string[] pieces = time.Split(':');

    return Convert.ToInt32(pieces[0]);
}

public static int GetMinute(string time)
{
    string[] pieces = time.Split(':');

    return Convert.ToInt32(pieces[1]);
}

public TimePickerPreference(Context ctxt, IAttributeSet attrs) : base(ctxt, attrs)
{

}


protected override View OnCreateDialogView()
{
    picker = new TimePicker(Context);
    picker.SetIs24HourView(Java.Lang.Boolean.True);
    return picker;
}

protected override void OnBindDialogView(View v)
{
    base.OnBindDialogView(v);

    picker.Hour = lastHour;
    picker.Minute = lastMinute;
}


protected override void OnDialogClosed(bool positiveResult)
{
    base.OnDialogClosed(positiveResult);

    if (positiveResult)
    {
        lastHour = picker.Hour;
        lastMinute = picker.Minute;

        string time = lastHour + ":" + lastMinute;
        if (lastMinute.ToString().Length == 1)
            time = lastHour + ":" + "0" + lastMinute;

        if (CallChangeListener(time))
        {
            PersistString(time);
        }

        Title = "שעת תזכורת: " + time;
    }
}

protected override Java.Lang.Object OnGetDefaultValue(TypedArray a, int index)
{
    return a.GetString(index);
}

protected override void OnSetInitialValue(bool restorePersistedValue, Java.Lang.Object defaultValue)
{
    string time = string.Empty;

    if (restorePersistedValue)
    {
        if (defaultValue == null)
        {
            time = GetPersistedString("00:00");
        }
        else
        {
            time = GetPersistedString(defaultValue.ToString());
        }
    }
    else
    {
        time = defaultValue.ToString();
    }

    lastHour = GetHour(time);
    lastMinute = GetMinute(time);
}

}

DialogPreference doesn't exist in the support libraries, and what seems to be instead is either PreferenceDialogFragment or PreferenceDialogFragmentCompat, both of which work differently, and the above code doesn't work with them.

I'm really at loss in all of this and would be glad for some help.
Thanks!