Tuesday, November 15, 2011

[android-developers] Re: DatePicker in a fragment

The solution I came up with was to subclass DialogFragment, returning
a DatePickerDialog in onCreate()

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

return new DatePickerDialog(sContext, dateSetListener,
sDate.get(Calendar.YEAR), sDate.get(Calendar.MONTH),
sDate.get(Calendar.DAY_OF_MONTH));

}

I implement DatePickerDialog.OnDateSetListener.onDateSet() in my
DateDialogFragment.

private DatePickerDialog.OnDateSetListener dateSetListener =
new DatePickerDialog.OnDateSetListener() {

@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {

Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
//call back to the DateDialogFragment listener
sListener.dateDialogFragmentDateSet(newDate);

}
};


I also define a listener interface in my DateDialogFragment for the
calling Activity/Fragment to implement.

public interface DateDialogFragmentListener{
public void dateDialogFragmentDateSet(Calendar date);
}

As you can see above, I fire my DateDialogFragmentListener from the
DatePickerDialog's listener.

I wrote about it in more detail with entire source here:
http://www.kylebeal.com/2011/11/android-datepickerdialog-and-the-dialogfragment/

On Nov 11, 1:55 pm, Kyle <park...@gmail.com> wrote:
> I am attempting to use a datepicker dialog based on the example athttp://developer.android.com/resources/tutorials/views/hello-datepick....
> This is obviously for an activity, but I'm trying to implement the
> same functionality in a fragment.  Using the code from the example
> won't work.  By this, I mean the following code snippet does not
> actually open the dialog:
>
> ...
> mPickDate = (Button) mRootView.findViewById(R.id.button_leave_date);
>
> // add a click listener to the button
> mPickDate.setOnClickListener(new View.OnClickListener() {
>        public void onClick(View v) {
>                 mActivity.showDialog(DATE_DIALOG_ID);
>        }});
>
> ...
>
> After reading various sources online, I know "showDialog" is
> deprecated and the recommendation is to use the DialogFragment.
> However, is there an option to generate a date picker dialog with this
> implementation?  I've been unable to find any good examples of anyone
> trying this - so if there are resources available to merge the
> (deprecated) example on the Android Developer web site with an actual
> DialogFragment implementation, I would really appreciate it.

--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

No comments:

Post a Comment