如何将datepicker保存到sharedpreferences [英] how to save datepicker to sharedpreferences
问题描述
是否有一种方法可以将日期选择器数据保存到共享首选项?如果是这样,您能给我一些如何做的代码吗?我将使用datepicker保存用户的出生日期.任何帮助,将不胜感激.
Is there a way to save a datepicker data to sharedpreferences? If so, can you give me some codes on how to do it? I'm going to use datepicker to save user's date of birth. Any help would be appreciated.
推荐答案
您可以通过环形交叉路口.根据DatePicker的年/月/日值,构造一个 java.util.Date
对象.然后在该对象上调用 getTime()
-它以非常长的数字(自1970年以来的毫秒数)返回日期,其数据类型为 long
.然后,您可以使用 putLong()
将其存储在 SharedPreferences
中,并使用 getLong()
进行检索.
You can, in a roundabout way. From the year/month/day values of the DatePicker, construct a java.util.Date
object. Then call getTime()
on that object - it would return the date as a very long number (# of milliseconds since year 1970) as datatype long
. Then you can store that in SharedPreferences
using putLong()
and retrieve it using getLong()
.
要将日期放回选择器,请使用 long
值构造一个 Date
对象,然后从中获取年/月/日.
To place the date back into the picker, construct a Date
object using the long
value, then retrieve year/month/day from it.
或者,您可以将年/月/日保存为三个单独的首选项.
Alternatively, you can save year/month/day as three separate preference items.
这是一个示例.DatePicker对象来自您应用程序中的某个位置-我不知道.
here's a sample. The DatePicker object comes from somewhere in your app - I wouldn't know.
DatePicker dp; //Where does this come from? You tell me.
Date d = new Date(dp.getYear(), dp.getMonth(), dp.getDay());
SharedPreferences Prefs = PreferenceManager.getDefaultSharedPreferences(Ctxt);
Prefs.edit().putLong("Birthday", d.getTime()).commit();
这篇关于如何将datepicker保存到sharedpreferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!