54

我正在使用谷歌示例使用对话框片段
http://developer.android.com/guide/topics/ui/controls/pickers.html在我的应用程序中插入一个日期选择器

但我不确定如何在设置日期后获取日期(不是 java 专家)。对话框和日期选择器运行正常,我可以记录正确设置的日期,但是,我怎样才能在父活动上执行回调?

这是我的对话框片段

public class DatePickerFragment extends DialogFragment implements
        DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        **Log.w("DatePicker","Date = " + year);**
    }
}

...我从我的活动中调用对话...

public void showDatePickerDialog(View v) {
    DialogFragment newFragment = new DatePickerFragment();
    newFragment.show(getSupportFragmentManager(), "datePicker");
}

在我的父活动中调用方法而不是 Log.w 的正确方法是什么?我想这与将回调作为参数或其他东西传递有关,但我在互联网上找到的大多数参考资料都是关于没有对话片段的先前版本

编辑:不确定它是否重要,但父活动被声明为:

public class EditSessionActivity extends FragmentActivity {

解决方案:感谢 Lecho 用户,这是这样做的方法

DatePickerFragment.class

public class DatePickerFragment extends DialogFragment{

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), (EditSessionActivity)getActivity(), year, month, day);
    }

}

...和父活动 EditSessionActivity.class ...

public class EditSessionActivity extends FragmentActivity implements OnDateSetListener {
...
    @Override
    public void onDateSet(DatePicker view, int year, int month, int day) {
        //do some stuff for example write on log and update TextField on activity
        Log.w("DatePicker","Date = " + year);
        ((EditText) findViewById(R.id.tf_date)).setText("Date = " + year);
    }
4

9 回答 9

64

DatePickerDialog构造函数foDatePickerDialog.OnDateSetListener作为第二个参数,所以也许你应该在你的父活动EditSessionActivity(而不是DatePickerFragment)中实现该接口并更改这一行:

return new DatePickerDialog(getActivity(), this, year, month, day);

进入这个:

return new DatePickerDialog(getActivity(), (EditSessionActivity)getActivity(), year, month, day);

然后您的活动应如下所示:

public class EditSessionActivity extends FragmentActivity implements
        DatePickerDialog.OnDateSetListener{

    public void onDateSet(DatePicker view, int year, int month, int day) {
        //use date in your activity
    }
    ...
}
于 2012-07-17T17:18:08.790 回答
25

我在显示日期选择器的类中简单地覆盖了日期选择器创建中的 onDateSet。请参见下面的代码:

  private OnClickListener onDateClicked() {
    return new OnClickListener() {
          @Override
          public void onClick(View v) {
             DialogFragment newFragment = new DatePickerFragment() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int day) {
                  salePaymentCustomView.setBtDateText("" + day + "/" + month+1 + "/" + year);
                }
             };
             newFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
    }
  };
 } 
于 2013-02-07T12:58:13.593 回答
14

该问题也可以在不将onDateSet方法移动到父活动的情况下解决。你只需要告诉在DatePickerFragment哪里搜索视图:

public class DatePickerFragment extends DialogFragment implements
    DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // do some stuff for example write on log and update TextField on activity
        Log.w("DatePicker","Date = " + year);
        ((TextView) getActivity().findViewById(R.id.tf_date)).setText("Date = " + year);
    }
}

我还将演员的目标从 更改EditTextTextView。这样,您可以为不同类型的视图重用您的实现,而不仅仅是EditText.

于 2013-05-11T23:14:58.443 回答
10

我对上述答案有一个更正。而不是像这样返回 DatePickerDialog

return new DatePickerDialog(getActivity(), (EditSessionActivity)getActivity(), year, month, day);

你应该以更通用的方式返回它

return new DatePickerDialog(getActivity(), (OnDateSetListener)getActivity(), 年月日);

只需确保您的活动实现 OnDateSetListener 接口并覆盖函数 onDateSet

@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) 
于 2014-01-25T06:50:14.767 回答
3
public void onDate(View view) {

        DialogFragment fragment = new SelectDateFragment();
        fragment.show(getFragmentManager(), "Date Picker");
    }

//  @SuppressLint("NewApi")
    class SelectDateFragment extends DialogFragment implements
            DatePickerDialog.OnDateSetListener {

        public Dialog onCreateDialog(Bundle savedInstanceState) {


            System.out.println("entrering on create dialog");;

            return new DatePickerDialog(getActivity(), this, mYear, mMonth,
                    mDay);//it will return dialog setting date with mYera,MMonth and MDay

        }

        @Override
        public void onDateSet(android.widget.DatePicker view, int year,
                int monthOfYear, int dayOfMonth) {
            System.out.println("year=" + year + "day=" + dayOfMonth + "month="
                    + monthOfYear);
            mYear=year;
            mMonth=monthOfYear;
            mDay=dayOfMonth;

            onPopulateSet(year, monthOfYear + 1, dayOfMonth);

        }
// set the selected date in the edit text  
        private void onPopulateSet(int year, int i, int dayOfMonth) {
            EditText et_setDate;
            et_setDate = (EditText) findViewById(R.id.register_et_dob);//register_et_dob:-id name of the edit text 
            et_setDate.setText(dayOfMonth + "/" + i + "/" + year);
            System.out.println("enetring on populate Set");

        }
于 2013-08-26T11:13:54.303 回答
3

如果您必须将结果返回到 Fragment,而不是 Activity,这里有一个完整的解决方案:

public class DatePickerDialogFragment extends DialogFragment  {

    private static final String ARGUMENT_YEAR = "ARGUMENT_YEAR";
    private static final String ARGUMENT_MONTH = "ARGUMENT_MONTH";
    private static final String ARGUMENT_DAY = "ARGUMENT_DAY";
    private DatePickerDialog.OnDateSetListener listener;

    private int year;
    private int month;
    private int dayOfMonth;

    public static DatePickerDialogFragment newInstance(final int year, final int month, final int dayOfMonth) {
        final DatePickerDialogFragment df = new DatePickerDialogFragment();
        final Bundle args = new Bundle();
        args.putInt(ARGUMENT_YEAR, year);
        args.putInt(ARGUMENT_MONTH, month);
        args.putInt(ARGUMENT_DAY, dayOfMonth);
        df.setArguments(args);
        return df;
    }

    @Override
    public void onCreate(@Nullable final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        retrieveArguments();
    }

    private void retrieveArguments() {
        final Bundle args = getArguments();
        if (args != null) {
            year = args.getInt(ARGUMENT_YEAR);
            month = args.getInt(ARGUMENT_MONTH);
            dayOfMonth = args.getInt(ARGUMENT_DAY);
        }
    }

    @Override
    public Dialog onCreateDialog(final Bundle savedInstanceState) {
        return new DatePickerDialog(getContext(), this.listener, this.year, this.month, this.dayOfMonth);
    }

    public void setListener(final DatePickerDialog.OnDateSetListener listener) {
        this.listener = listener;
    }
}

然后只需在 Fragment 或 Activity 中使用它:

final Calendar c = Calendar.getInstance();
DatePickerDialogFragment datePicker = DatePickerDialogFragment.newInstance(
        c.get(Calendar.YEAR),
        c.get(Calendar.MONTH),
        c.get(Calendar.DAY_OF_MONTH));
datePicker.setListener(this);
datePicker.show(getChildFragmentManager(), null);
于 2018-05-30T20:33:20.837 回答
2

Leszek 的答案有效,但如果对话框是从另一个片段开始的,则无效。在这种情况下,您需要setTargetFragment()在创建对话框的代码和getTargetFragment()对话框代码中使用。

在创建对话框的代码中:

DialogFragment dialogFragment = new YourDialogFragment();
dialogFragment.setTargetFragment(YourParentFragment.this, 0);
dialogFragment.show(getFragmentManager(), "mydialog");

在 DialogFragment 代码中:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
    DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener()
    {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
        {
            YourParentFragment parentFragment = (YourParentFragment) getTargetFragment();
            // Manipulate the parent fragment
            // ...
        }
    };
    // Get the initial date
    // ...
    return new DatePickerDialog(getActivity(), listener, year, month, day);
}
于 2017-02-22T11:44:32.040 回答
0

我遇到了类似的问题,但是我的日期选择器是从另一个片段中的对话框片段启动的。这使得处理回调变得非常困难,因为它们想要返回主活动,而我希望数据返回到前一个对话框片段。

最初,我将新的日期值传递给主活动(使用 OnDateSetListener),并打算使用启动日期选择器的对话框来获取它们,但是当日期选择器关闭时,该对话框中没有触发生命周期事件。

我得到的结果是在日期选择器的 onDismiss 中,实例化一个新的对话框片段,在其上调用 set results 方法,然后启动它。当然,为此您需要确保前一个片段在启动日期选择器时被关闭。

这是调用日期选择器的 dialogFragment

public class NewTrialDialogFragment extends DialogFragment  {

public final String LOG_TAG = "NewTrialDialog Fragment";

Button startDateButton;
Integer newYear, newMonth, newDay;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.dialog_new_trial, container, false);
    getDialog().setTitle("Dialog New Trial");

    startDateButton = (Button) rootView.findViewById(R.id.button_start_date);
    startDateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDatePickerDialog(v);
        }
    });

    //If you exit the datepicker without choosing anything, it returns zeros
    if (newYear != null && newMonth != null && newDay != null && newYear != 0) {
        startDateButton.setText(newYear + " " + newMonth + " " + newDay);
    }else{
        startDateButton.setText("Select Start Date");
    }

     return rootView;
}

public void showDatePickerDialog(View v) {
    TrialDatePickerDialog newDialog = new TrialDatePickerDialog();
    newDialog.show(getActivity().getSupportFragmentManager(), "datePicker");
    this.dismiss();
}

public void setDates(int year, int month, int day){
    newYear = year;
    newMonth = month;
    newDay = day;
}}

和日期选择器

public  class TrialDatePickerDialog extends DialogFragment implements DatePickerDialog.OnDateSetListener
     {

private final String LOG_TAG = "TrialDatePickerDialog";
int newYear, newMonth, newDay;


@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the current date as the default date in the picker
    final Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);

    // Create a new instance of TrialDatePickerDialog and return it
    return new DatePickerDialog(getActivity(), this , year, month, day);
}

         @Override
         public void onDismiss(DialogInterface dialog) {
             super.onDismiss(dialog);
             FragmentManager fm = getActivity().getSupportFragmentManager();
             NewTrialDialogFragment newTrialDialogFragment = new NewTrialDialogFragment();
             newTrialDialogFragment.setDates(newYear, newMonth, newDay);
             newTrialDialogFragment.show(fm, "new_trial_dialog");

         }

         @Override
         public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
             newYear = year;
             newMonth = monthOfYear;
             newDay = dayOfMonth;
         }
     }
于 2016-04-17T08:19:55.227 回答
0

科特林版本。

DatePickerFragment 类:

class DatePickerFragment : DialogFragment() {

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

        val c = Calendar.getInstance()
        val year = c.get(Calendar.YEAR)
        val month = c.get(Calendar.MONTH)
        val day = c.get(Calendar.DAY_OF_MONTH)

        return DatePickerDialog(context!!, context!! as MainActivity, year, month, day)
    }
}

DatePickerDialog.OnDateSetListener移至 MainActicity

class MainActivity : AppCompatActivity(), DatePickerDialog.OnDateSetListener {

    ..

    override fun onDateSet(view: DatePicker, year: Int, month: Int, day: Int) {
        //use date in your activity
    }
}
于 2019-11-04T02:42:27.530 回答