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

旧城冷巷雨未停 提交于 2019-12-03 00:35:17

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().

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!