1

有人问过这个问题的许多变体,我一直在看答案,直到我睁一只眼闭一只眼,但我就是看不到。我有一个应用程序/活动正在处理多种类型的计划,并调用了一个片段(我将命名为 cs2255)来处理特定类型的计划。片段 cs2255 想要从用户那里获取日期,因此,按照指南和示例,响应按钮单击,它具有以下代码:

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

StartDatePickerFragment 看起来像:

public class StartDatePickerFragment extends DialogFragment
            implements DatePickerDialog.OnDateSetListener {

    private DatePickedListener mCallBack;
    // Our host activity must implement this.
    public interface DatePickedListener {
        // we call with our return values
        public void onDatePicked(int aYear, int aMonth, int aDay);
    }


    @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 pYear, int pMonth, 
                         int pDay) {
        // What To Do Here???
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // Makes sure our container/host has implemented
        // the callback interface. If not, it throws an exception.
        try {
            mCallback = (OnDatePickedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                + " must implement OnDatePickedListener");
        }
    }
}

从活动调用等效的 StartDatePickerFragment 的答案示例相对简单,并使用包或回调接口返回结果,但我不是直接从活动调用,所以我认为这不起作用。从片段调用它的示例似乎都通过在本地存储或显示数据而不将其传递回调用者来绕过问题。我不想将日期选择器逻辑移回基本活动,因为它不需要知道具体时间表的详细信息,或者即使它需要放置一个日期选择器。但是我怎样才能通过可重用的设计完成片段到片段的通信呢?

当片段实际上由活动托管时,我已经添加了过去使用过的代码段。我实际上没有在这里尝试过这种技术,因为 onAttach 方法接收一个 Activity 参数(启动 cs2255 的活动),但它不是接口的实现者。片段 cs2255 将是实现者,因此我相信 ClassCastException 将被抛出。

4

0 回答 0