简体   繁体   English

如何在片段中实现Android日期选择器

[英]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. 提前感谢。

Use this CustomDialogFragment that contains use of 使用包含以下内容的CustomDialogFragment

  1. TimePicker Dialog fragment TimePicker对话框片段
  2. DatePicker Dialog fragment DatePicker对话框片段
  3. Simple Dialog Fragment 简单对话框片段

    CustomeDialogFragment Class CustomeDialogFragment类

public class CustomDialogFragment extends DialogFragment { 公共类CustomDialogFragment扩展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) 1)在您的Activity或fragment中实现OnDateSetListener (完成后,它将结果返回到onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)方法)

2) Call DatePicker From Fragment Like this way 2)从片段中调用DatePicker

   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 并以这种方式从Activity(或FragmentActivity)调用DatePicker

               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 . &根据设置"dialog_id"根据通过捆绑包将数据发送到CustomDialogFragment可以使用TIME_PICKER (用于时间选择器对话框)和DIALOG (用于简单对话框)来发送"dialog_id"

As my knowledge, cannot use showDialog() in Fragment. 据我所知,不能在Fragment中使用showDialog() It's also deprecated. 也已弃用。 Use DialogFragment . 使用DialogFragment Learn from this tutorial as you need http://www.kylebeal.com/2011/11/android-datepickerdialog-and-the-dialogfragment/ 根据需要从本教程中学习http://www.kylebeal.com/2011/11/android-datepickerdialog-and-the-dialogfragment/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM