如何在Android偏好设置中设置日期和时间?

时间:2014-08-13 09:02:15

标签: android android-preferences

我想在偏好中设置日期和时间。在我的应用程序中,我使用自定义日期和时间对话框,并希望设置时间和时间。首选项中的日期从该对话框中选择。

显示日期和时间选择器对话框的功能:

public void showDialog() {
    // TODO Auto-generated method stub
    Dialog dialog = new Dialog(MainActivity.this);

    dialog.setContentView(R.layout.date_time_dialog);
    dialog.setTitle("Custom Dialog");
    set_time = (Button) dialog.findViewById(R.id.set_time);
    dialog.show();
    timepk = (TimePicker)dialog.findViewById(R.id.timePicker1);
    final Calendar c = Calendar.getInstance();
    hour = c.get(Calendar.HOUR_OF_DAY);
    min = c.get(Calendar.MINUTE);
    timepk.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
        public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
            hour = hourOfDay;
            min = minute;

        }
    });
    datepk = (DatePicker)dialog.findViewById(R.id.datePicker1);
    final Calendar cal = Calendar.getInstance();
    Year = cal.get(Calendar.YEAR);
    month = cal.get(Calendar.MONTH);
    day = cal.get(Calendar.DAY_OF_MONTH);

    datepk.init(Year, month, day, new OnDateChangedListener() {

        @Override
        public void onDateChanged(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            // TODO Auto-generated method stub
            Year = year;
            month = monthOfYear;
            day = dayOfMonth;
        }
    });

在共享偏好设置中保存日期和时间的功能:

public void setTime(){
    SharedPreferences prefer = getSharedPreferences("MyPREFERENCES", 0);
    SharedPreferences.Editor preferencesEditor = prefer.edit();
    preferencesEditor.putInt("Year",Year);
    preferencesEditor.putInt("Month",month);
    preferencesEditor.putInt("Day",day);
    preferencesEditor.putInt("Hour",hour);
    preferencesEditor.putInt("Min",min);
    Boolean flag = preferencesEditor.commit();
    if(flag==true)
    {
        Toast.makeText(getApplicationContext(),
                "Time saved sucessfully!",
                Toast.LENGTH_LONG).show();
    }
}

2 个答案:

答案 0 :(得分:1)

存储单个long可能是更好的选择,而不是将日期的每个部分存储为单独的首选项。以下示例(也在this gist中发布)是一个首选项,它会扩展DialogPreference以弹出一个时间要求(这只是时间,但您可以将时间选择器换成日期选择器并轻松更新onDialogClosed中的值。它还实现了OnPreferenceChangeListener,以便您可以在设置新首选项时执行某些操作(例如,它将摘要更新为新的时间集):

import android.content.Context;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TimePicker;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;

public class TimePreference extends DialogPreference implements Preference.OnPreferenceChangeListener {
    private TimePicker picker = null;
    public final static long DEFAULT_VALUE = 0;

    public TimePreference(final Context context, final AttributeSet attrs) {
        super(context, attrs, 0);
        this.setOnPreferenceChangeListener(this);
    }

    protected void setTime(final long time) {
        persistLong(time);
        notifyDependencyChange(shouldDisableDependents());
        notifyChanged();
    }

    protected void updateSummary(final long time) {
        final DateFormat dateFormat = android.text.format.DateFormat.getTimeFormat(getContext());
        final Date date = new Date(time);
        setSummary(dateFormat.format(date.getTime()));
    }

    @Override
    protected View onCreateDialogView() {
        picker = new TimePicker(getContext());
        picker.setIs24HourView(android.text.format.DateFormat.is24HourFormat(getContext()));
        return picker;
    }

    protected Calendar getPersistedTime() {
        final Calendar c = Calendar.getInstance();
        c.setTimeInMillis(getPersistedLong(DEFAULT_VALUE));

        return c;
    }

    @Override
    protected void onBindDialogView(final View v) {
        super.onBindDialogView(v);
        final Calendar c = getPersistedTime();

        picker.setCurrentHour(c.get(Calendar.HOUR_OF_DAY));
        picker.setCurrentMinute(c.get(Calendar.MINUTE));
    }

    @Override
    protected void onDialogClosed(final boolean positiveResult) {
        super.onDialogClosed(positiveResult);

        if (positiveResult) {
            final Calendar c = Calendar.getInstance();
            c.set(Calendar.MINUTE, picker.getCurrentMinute());
            c.set(Calendar.HOUR_OF_DAY, picker.getCurrentHour());


            if (!callChangeListener(c.getTimeInMillis())) {
                return;
            }

            setTime(c.getTimeInMillis());
        }
    }

    @Override
    protected Object onGetDefaultValue(final TypedArray a, final int index) {
        return a.getInteger(index, 0);
    }

    @Override
    protected void onSetInitialValue(final boolean restorePersistedValue, final Object defaultValue) {
        long time;
        if (defaultValue == null) {
            time = restorePersistedValue ? getPersistedLong(DEFAULT_VALUE) : DEFAULT_VALUE;
        } else if (defaultValue instanceof Long) {
            time = restorePersistedValue ? getPersistedLong((Long) defaultValue) : (Long) defaultValue;
        } else if (defaultValue instanceof Calendar) {
            time = restorePersistedValue ? getPersistedLong(((Calendar)defaultValue).getTimeInMillis()) : ((Calendar)defaultValue).getTimeInMillis();
        } else {
            time = restorePersistedValue ? getPersistedLong(DEFAULT_VALUE) : DEFAULT_VALUE;
        }

        setTime(time);
        updateSummary(time);
    }

    @Override
    public boolean onPreferenceChange(final Preference preference, final Object newValue) {
        ((TimePreference) preference).updateSummary((Long)newValue);
        return true;
    }
}

答案 1 :(得分:0)

如果您觉得以毫安存储时间感觉不舒服,可以这样做:

public void storeDate(Date theDate){
   SimpleDateFormat df = new SimpleDateFormat();
   df.applyPattern("yyyy/MM/dd HH:mm"); //this is the SQLite timedate pattern

   SharedPreferences pm = PreferenceManager.getDefaultSharedPreferences(MyActivity.this);
   pm.getEditor().putString("date_key", df.format(theDate));
}

public Date retrieveDate() {
   SimpleDateFormat df = new SimpleDateFormat();
   df.applyPattern("yyyy/MM/dd HH:mm"); //this is the SQLite timedate pattern

   SharedPreferences pm = PreferenceManager.getDefaultSharedPreferences(MyActivity.this);
   return df.parse(pm.getString("date_key"));  //this may throw an exception you should handle

}