如何将日期传回 DialogFragment

How to pass date back to a DialogFragment

我有一个 DialogFragment,它打开另一个实现 DatePicker 的 DialogFragment,我想将 DatePicker 中的日期传回前一个 DialogFragment 并将其显示在 EditText 上。我找到了将日期传回主 activity 的方法,但找不到将其传回之前的 DialogFragment 的方法。 请帮助。

我使用这里的示例来添加 DatePicker: https://neurobin.org/docs/android/android-date-picker-example/

这是我代码中的 classes: 主要活动

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btn = (Button) findViewById(R.id.btn);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            DialogFragment newFragment = new MyDialogFragment();
            newFragment.show(getSupportFragmentManager(), "DialogFragment");
        }
    });

}

MyDialogFragment

public class MyDialogFragment extends DialogFragment {
EditText edTo;


View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.popup, container, false);
    getDialog().setTitle("Set Date Range");

    edTo = (EditText) rootView.findViewById(R.id.etDateTo);
    edTo.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int action = event.getAction();
            if (action == MotionEvent.ACTION_DOWN) {

                DialogFragment newFragment = new DatePickerFragment();
                newFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
            }
            return false;
        }
    });

    return rootView;
}

}

DatePicker片段 public class DatePickerFragment 扩展 DialogFragment 实现 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);
}


@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
       // Do something with the date chosen by the user

    EditText etDateTo= (EditText) getActivity().findViewById(R.id.tv);
    etDateTo.setText("Year: "+year+" Month: "+monthOfYear+" Day: "+dayOfMonth);

}

}

这是打开 DatePicker 的 MyDialogFragment enter image description here

为了从片段接收​​事件回调,承载它的 activity 必须实现该接口。

https://developer.android.com/training/basics/fragments/communicating.html

EventBus 帮我解决了这个问题。我使用了此 link 中的示例,因为任何人都面临同样的问题。 http://www.cardinalsolutions.com/blog/2015/02/event-bus-on-android 谢谢,