每当onDateSet方法调用容器片段时,如何从DialogFragment获取Date

时间:2016-11-04 19:06:47

标签: android

我希望每当调用DialogFragment的onDataSet到名为FromToDateFragment.java的容器片段时都会得到日期。代码 的 FromDatePicker.java:

String keyDate;

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    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);

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

public void onDateSet(DatePicker view, int year, int month, int day) {
    keyDate = String.valueOf(new StringBuilder().append(day).append("/").append(month+1).append("/").append(year));

}
}

在上面的类中,只要用户设置日期,onDateSet方法就会调用并设置keyDate变量的值。现在我想把这个日期发送到名为FromToDateFragment.java的容器片段。

FromToDateFragment.java

public class FromToDateFragment extends Fragment implements View.OnClickListener{
    String keyFromDate, keyToDate = null;
//    getFromToDateFromFromToDateFragment getDate;
    SessionManager sessionManager;
    TextView fromDateTextView;
    TextView toDateTextView;
    String fromDate, toDate;



@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.from_to_date_fragment, container, false);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        FragmentManager manager = getFragmentManager();
        switch (id) {
            case R.id.from_date:
                DialogFragment from = new FromDatePicker();
                from.show(manager, "fromDatePicker");
                break;
            case R.id.to_date:
                DialogFragment to = new ToDatePicker();
                to.show(manager, "toDatePicker");
                break;
        }
    }

在这个片段中,我只是通过此代码显示此diaglogFragment

DialogFragment from = new FromDatePicker();
                from.show(manager, "fromDatePicker");

单击按钮时。请告诉我如何在FromToDateFragment.java类中获取日期。

1 个答案:

答案 0 :(得分:0)

通过setter将OnDateSetListener的实现传递给片段FromDatePickerToDatePicker,而不是让它们自己实现