Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use DatePickerDialog as a Preference

Tags:

I have preferences working and I am using a combination of CheckBoxPreference and EditTextPreference. I would like to replace one of them with a DatePickerDialog.

When my settings screen is showing, if you click on one of the preferences, I would like the date picker dialog to pop up for the user to select a date, and save the picked date in preferences. I have seen this work in other apps, but I cannot see how to do this.

I have the date picker dialog working from a regular view (as per tutorial), but I would to like to use it from a preference.

like image 274
mlw Avatar asked Nov 18 '10 14:11

mlw


2 Answers

Thanks to @commonsware. I followed his project and created a date picker preference dialog. So it will help someone.

Follow the steps to open date picker in preference window.

1 . Create a custom dialog preference for date picker.

package com.packagename;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.content.Context;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.DatePicker;

public class DatePreference extends DialogPreference {
    private int lastDate = 0;
    private int lastMonth = 0;
    private int lastYear = 0;
    private String dateval;
    private CharSequence mSummary;
    private DatePicker picker = null;
    public static int getYear(String dateval) {
        String[] pieces = dateval.split("-");
        return (Integer.parseInt(pieces[0]));
    }

    public static int getMonth(String dateval) {
        String[] pieces = dateval.split("-");
        return (Integer.parseInt(pieces[1]));
    }

    public static int getDate(String dateval) {
        String[] pieces = dateval.split("-");
        return (Integer.parseInt(pieces[2]));
    }

    public DatePreference(Context ctxt, AttributeSet attrs) {
        super(ctxt, attrs);

        setPositiveButtonText("Set");
        setNegativeButtonText("Cancel");
    }

    @Override
    protected View onCreateDialogView() {
        picker = new DatePicker(getContext());

        // setCalendarViewShown(false) attribute is only available from API level 11
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            picker.setCalendarViewShown(false);
        }

        return (picker);
    }

    @Override
    protected void onBindDialogView(View v) {
        super.onBindDialogView(v);

        picker.updateDate(lastYear, lastMonth + 1, lastDate);
    }

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

        if (positiveResult) {
            lastYear = picker.getYear();
            lastMonth = picker.getMonth();
            lastDate = picker.getDayOfMonth();

            String dateval = String.valueOf(lastYear) + "-"
                    + String.valueOf(lastMonth) + "-"
                    + String.valueOf(lastDate);

            if (callChangeListener(dateval)) {
                persistString(dateval);
            }
        }
    }

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

    @Override
    protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
        dateval = null;

        if (restoreValue) {
            if (defaultValue == null) {
                Calendar cal = Calendar.getInstance();
                SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
                String formatted = format1.format(cal.getTime());
                dateval = getPersistedString(formatted);
            } else {
                dateval = getPersistedString(defaultValue.toString());
            }
        } else {
            dateval = defaultValue.toString();
        }
        lastYear = getYear(dateval);
        lastMonth = getMonth(dateval);
        lastDate = getDate(dateval);
    }

    public void setText(String text) {
        final boolean wasBlocking = shouldDisableDependents();

        dateval = text;

        persistString(text);

        final boolean isBlocking = shouldDisableDependents();
        if (isBlocking != wasBlocking) {
            notifyDependencyChange(isBlocking);
        }
    }

    public String getText() {
        return dateval;
    }

    public CharSequence getSummary() {
        return mSummary;
    }

    public void setSummary(CharSequence summary) {
        if (summary == null && mSummary != null || summary != null
                && !summary.equals(mSummary)) {
            mSummary = summary;
            notifyChanged();
        }
    }
}

2 . Add the following code in preference xml located in "res/xml/yourpreference.xml"

<com.packagename.DatePreference 
android:key="keyname" 
android:title="Title of the preference" 
android:defaultValue="2014-08-01" 
android:summary="Summary"/>

Note: Change the "keyname","Title of the preference","2014-08-01","summary" as of your requirement

3 . If you want to change the default vaules through Preference Activity use the following code.

package com.packagename;

import android.os.Bundle;
import com.packagename.DatePreference;

public class CustomPreference extends PreferenceActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    addPreferencesFromResource(R.xml.preferences);

    final DatePreference dp= (DatePreference) findPreference("keyname");
    dp.setText("2014-08-02");
    dp.setSummary("2014-08-02");
    dp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference,Object newValue) {
            //your code to change values.
            dp.setSummary((String) newValue);
            return true;
        }
    });

  }
}

Now Enjoy...

like image 161
Mahendran Sakkarai Avatar answered Oct 21 '22 13:10

Mahendran Sakkarai


Here's an implementation ready to use in your project as a lib.

To quote the source:

Use it just like any other preference in your PreferenceScreen XML:

<org.bostonandroid.datepreference.DatePreference
      android:key="dob" android:title="@string/dob"
      android:defaultValue="1991.01.01" />
like image 34
JWL Avatar answered Oct 21 '22 13:10

JWL