Custom DatePicker as Preference does not keep value when user edits value in field

前端 未结 3 1065
攒了一身酷
攒了一身酷 2021-02-04 19:09

I created a DatePickerPreference, i.e. I extended DialogPreference and created a DatePicker object inside and had it working almost perfectly. It changes values when you click t

相关标签:
3条回答
  • 2021-02-04 19:21

    Please take a look at the DatePreference library:

    http://mikeburnscoder.wordpress.com/2010/09/27/datepreference-an-android-library/
    https://github.com/bostonandroid/DatePreference

    This should solve your problem.

    0 讨论(0)
  • 2021-02-04 19:26

    I had the same issue. The solution is very simple. The date picker updates the edited values only when it losts focus, so before getting the values you have to call:

    datePicker.clearFocus();
    

    After this call you can call:

    selectedDay = datePicker.getDayOfMonth();
    selectedMonth = datePicker.getMonth();
    

    and have the values updated.

    0 讨论(0)
  • 2021-02-04 19:38

    Since this class extends the DialogPreference class, it already handles changing the SharedPreference using the buttons. To correctly update your date variable after the user types the new date, you need to update the SharedPreference manually.

    You can do this as follows:

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor preferences = prefs.edit();
    preferences.putLong("mdate_key", mDate.getTime());
    preferences.commit();
    

    Here, mdate_key will correspond to the DatePickerPreference key used in the PreferenceActivity XML file.

    I recommend either doing this in onDateChanged() or onDestroy().

    0 讨论(0)
提交回复
热议问题