Rose18
Rose18

Reputation: 3162

How to implement Android date picker in a fragment

I have implemented a date picker as following.

private void updateDisplay() {
    String str_date = "";
    if ((Month + 1) >= 10) {
        if (Day < 10) {
            str_date = Year + "-" + (Month + 1) + "-0" + Day;
        } else {
            str_date = Year + "-" + (Month + 1) + "-" + Day;
        }
    } else {
        if (Day < 10) {
            str_date = Year + "-0" + (Month + 1) + "-0" + Day;
        } else {
            str_date = Year + "-0" + (Month + 1) + "-" + Day;
        }

    }
    date.setText("" + str_date);
}

protected void onPrepareDialog(int id, Dialog dialog) {
    switch (id) {
    case DATE_DIALOG_ID:
        ((DatePickerDialog) dialog).updateDate(Year, Month, Day);
        break;
    }
}

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
        return new DatePickerDialog(viewLoad.getContext(),
                mDateSetListener, Year, Month, Day);
    }
    return null;
}

private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {
        Year = year;
        Month = monthOfYear;
        Day = dayOfMonth;
        updateDisplay();
    }
};

Here is my code segment for button.

@Override
public void onClick(View view) {
    switch (view.getId()) {
    case R.id.btnDate:
        showDialog(DATE_DIALOG_ID);
        break;

This works fine. Now the problem is I need to implement a date picker in a fragment. Can anyone plz explain how to do it.

Edited Code

 private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {
        Year = year;
        Month = monthOfYear;
        Day = dayOfMonth;
        updateDisplay();
    }
};

Thanx in advance.

Upvotes: 1

Views: 1481

Answers (2)

Dixit Patel
Dixit Patel

Reputation: 3192

Use this CustomDialogFragment that contains use of

  1. TimePicker Dialog fragment
  2. DatePicker Dialog fragment
  3. Simple Dialog Fragment

    CustomeDialogFragment Class

public class CustomDialogFragment extends DialogFragment {

            public static final int DATE_PICKER = 1;
            public static final int TIME_PICKER = 2;
            public static final int DIALOG = 3;

            Context mContext;
            String mMessage;
            boolean finishActivity;

           // private Fragment mCurrentFragment;
            Activity mActivity;

            /**
             *  this constructor is used for datepicker & Timepicker
             */
            public CustomDialogFragment (Fragment fragment ) {
            //        mCurrentFragment = fragment;
            }

            public CustomDialogFragment (Activity mActivity ) {
                this.mActivity = mActivity;
        }

            /**
             *  this constructor is used for simple dialog fragment
             */
            public CustomDialogFragment(Context context, String message, final boolean finishActivity) {
                mContext = context;
                mMessage = message;
                this.finishActivity = finishActivity;
            }



            public Dialog onCreateDialog(Bundle savedInstanceState) {
                Bundle bundle = new Bundle();
                bundle = getArguments();
                int id = bundle.getInt("dialog_id");
                switch (id) {
                case DATE_PICKER:
                    return new DatePickerDialog(getActivity(),
                            (OnDateSetListener)mActivity, bundle.getInt("year"),
                            bundle.getInt("month"), bundle.getInt("day"));

               case TIME_PICKER:
                    return new TimePickerDialog(getActivity(),
                            (OnTimeSetListener)mActivity,bundle.getInt("hour"),
                            bundle.getInt("minute"), true);

               case DIALOG:
                   AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
                   alertDialogBuilder.setTitle(R.string.app_name);
                   alertDialogBuilder.setMessage(mMessage);
                   alertDialogBuilder.setIcon(R.drawable.ic_launcher);
                   alertDialogBuilder.setCancelable(false);
                   alertDialogBuilder.setPositiveButton(
                            getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {

                       @Override
                       public void onClick(DialogInterface dialog, int arg1) {

                           dialog.dismiss();
                           if (finishActivity == true) {
                               Activity act = (Activity) mContext;
                               act.finish();
                           }

                       }
                   });
                   alertDialogBuilder.setNegativeButton(getResources().getString(R.string.cancel_btn_title), new DialogInterface.OnClickListener() {

                       @Override
                       public void onClick(DialogInterface dialog, int which) {
                           CustomDialogFragment.this.dismiss();
                       }
                   });


                   return alertDialogBuilder.create();

                }

               //Define your custom dialog or alert dialog here and return it.
               return new Dialog(getActivity());
            }
        }

& Use date Picker this Way

1) In your Activity Or fragment Implement OnDateSetListener ( after done it will get back result to onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) method)

2) Call DatePicker From Fragment Like this way

   CustomDialogFragment dialog = new CustomDialogFragment(YourFragment.this);
    Bundle bundle = new Bundle();
    bundle.putInt("dialog_id", CustomDialogFragment.DATE_PICKER);
    bundle.putInt("year", mYear);
    bundle.putInt("month", mMonth);
    bundle.putInt("day", mDay);
    dialog.setArguments(bundle);
    dialog.show(getFragmentManager(), "dialog"); 

& Call DatePicker From Activity(or FragmentActivity) Like this Way

               CustomDialogFragment dialog = new CustomDialogFragment(this);
                Bundle bundle = new Bundle();
                bundle.putInt("dialog_id", CustomDialogFragment.DATE_PICKER);
                bundle.putInt("year", mYear);
                bundle.putInt("month", mMonth);
                bundle.putInt("day", mDay);
                dialog.setArguments(bundle);
                dialog.setCancelable(false);
                dialog.show(this.getSupportFragmentManager(), "dialog");

& as per Set "dialog_id" u can use TIME_PICKER (for time picker dialog) & DIALOG(for simple dialog) as per send "dialog_id" according to send data through bundle to CustomDialogFragment.

Upvotes: 2

Thein
Thein

Reputation: 3968

As my knowledge, cannot use showDialog() in Fragment. It's also deprecated. Use DialogFragment. Learn from this tutorial as you need http://www.kylebeal.com/2011/11/android-datepickerdialog-and-the-dialogfragment/

Upvotes: 0

Related Questions