onAttach()从未在DialogFragment中调用过

时间:2012-12-28 13:30:33

标签: android callback android-fragments android-dialog android-dialogfragment

我尝试从DialogFragment实现回调。 有一个很好的示例,但他们不会从DialogFragment打开此Fragmenthttp://developer.android.com/guide/topics/ui/dialogs.html#PassingEvents

所以这是我的代码:

public class EditDateDialogFragment extends DialogFragment {
    // Use this instance of the interface to deliver action events
    EditDateDialogListener mListener;

    /* The activity that creates an instance of this dialog fragment must
     * implement this interface in order to receive event callbacks.
     * Each method passes the DialogFragment in case the host needs to query it. */
    public interface EditDateDialogListener {
        public void onDialogPositiveClick(DialogFragment dialog);
        public void onDialogNegativeClick(DialogFragment dialog);
    }


    public static EditDateDialogFragment newInstance( int currentCategoryId ) {
        EditDateDialogFragment p = new EditDateDialogFragment();
        Bundle args = new Bundle();
        args.putInt("currentRecordId", currentCategoryId);
        p.setArguments(args);
        return p;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        mCurrentRecordId = getArguments().getInt("currentRecordId");
        super.onCreate(savedInstanceState);
    }

    public void onAttach(SherlockActivity activity) {

        super.onAttach(activity);

        try {
            // Instantiate the EditDateDialogListener so we can send events to the host
            mListener = (EditDateDialogListener) activity;
        } catch (ClassCastException e) {
            // The activity doesn't implement the interface, throw exception
            throw new ClassCastException(activity.toString() + " must implement EditDateDialogListener");
        }

    }

        @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        final View v = inflater.inflate(R.layout.fragment_dialog_edit_date, null);

        return new AlertDialog.Builder(getActivity()).setTitle("Set Date...").setView(v).setCancelable(true).setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.d("", "Dialog confirmed");

                mListener.onDialogPositiveClick(EditDateDialogFragment.this);

            }
        }).setNegativeButton("Abort", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.d("", "Dialog abort");
                dialog.cancel();
            }
        }).create();
    }
}

在RecordDetailFragment.java中,我实现了接口并以这种方式创建了EditDateDialogFragment的新实例(只是重要的部分):

public class RecordDetailFragment extends SherlockFragment implements EditDateDialogFragment.EditDateDialogListener {
...
 DialogFragment editDateFragment = EditDateDialogFragment.newInstance( recordId );
             editDateFragment.show(getActivity().getSupportFragmentManager(), "EditDateDialogFrame");
@Override
    public void onDialogPositiveClick(DialogFragment dialog) {
        LOGD(TAG, "Overriden Dialog confirmed");
        //((EditDateDialogFragment) dialog).mDatePicker;

    }

    @Override
    public void onDialogNegativeClick(DialogFragment dialog) {
        // TODO Auto-generated method stub

    }
...
}

现在永远不会调用onAttach(SherlockActivity activity)中的公开无效EditDateDialogFragment,因为我是从DialogFragment而不是Fragment创建Activity的? 如何解决这个问题?

更新: 在RecordDetailFragment中,我将其插入到onCreate()

if (savedInstanceState != null) {
    EditDateDialogFragment dpf = (EditDateDialogFragment) getActivity().getSupportFragmentManager().findFragmentByTag("EditDateDialogFragment");
    if (dpf != null) {
        dpf.setListener((EditDateDialogListener) this);
    }
}

我将DialogFragment的实例化更改为

 EditDateDialogFragment editDateFragment = EditDateDialogFragment.newInstance( recordId );
             editDateFragment.setListener((EditDateDialogListener) this);
             editDateFragment.show(getActivity().getSupportFragmentManager(), "EditDateDialogFragment");

注意EditDateDialogFragment而不是DialogFragment。 我不确定如何在对话框中更新引用。

4 个答案:

答案 0 :(得分:10)

刚刚遇到同样的问题,解决方案非常简单。而不是覆盖

public void onAttach(Context context) {}

重写:

public void onAttach(Activity activity) {}

DialogFragment现在一切正常。

答案 1 :(得分:9)

  

如何解决这个问题?

我猜你希望RecordDetailFragment实例的行为与EditDateDialogListener的{​​{1}}相同。如果是,则需要将其显式设置(并更新)为侦听器:

DialogFragment

其中DialogFragment editDateFragment = EditDateDialogFragment.newInstance( recordId ); editDataFragment.setListener(RecordDetailFragment.this); editDateFragment.show(getActivity().getSupportFragmentManager(), "EditDateDialogFrame"); setListener()中的方法,如下所示:

EditDialogFragment

例如,当用户旋转手机时,将重新创建活动及其片段,您需要重新设置监听器以指向新创建的public void setListener(EditDateDialogListener listener) { mListener = listener; } 实例(您可能希望使用{ {1}} RecordDetailFragment。您可以找到类似的内容in this answer(您将在WeakReference中查找两个片段)。

修改:在mListener的{​​{1}}方法中:

onCreate

答案 2 :(得分:3)

onCreateDialog中的某处将mListener强制转换为getActivity():

try {
    mListener = (EditDateDialogListener) getActivity();
} catch (Exception e) {
    throw new ClassCastException(getActivity().toString()
            + " must implement EditDateDialogListener");
}

答案 3 :(得分:-3)

好的,我认为它现在有效。 我的解决方案:

   public class EditDateDialogFragment extends DialogFragment {
            // Use this instance of the interface to deliver action events
    EditDateDialogListener mListener = new EditDateDialogListener() {

        @Override
        public void onDialogPositiveClick(DialogFragment dialog) {
            //Should always overridden by interface implementing class
        }

        @Override
        public void onDialogNegativeClick(DialogFragment dialog) {
            //Should always overridden by interface implementing class
        }
    };
        DatePicker mDatePicker;

        /*
         * The activity that creates an instance of this dialog fragment must
         * implement this interface in order to receive event callbacks. Each method
         * passes the DialogFragment in case the host needs to query it.
         */
        public interface EditDateDialogListener {
            public void onDialogPositiveClick(DialogFragment dialog);

            public void onDialogNegativeClick(DialogFragment dialog);
        }

        public void setListener(EditDateDialogListener listener) {
            mListener = listener;
        }

        public static EditDateDialogFragment newInstance(int currentCategoryId) {
            EditDateDialogFragment p = new EditDateDialogFragment();
            Bundle args = new Bundle();
            args.putInt("currentRecordId", currentCategoryId);
            p.setArguments(args);
            return p;
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            mCurrentRecordId = getArguments().getInt("currentRecordId");
            super.onCreate(savedInstanceState);
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            LayoutInflater inflater = LayoutInflater.from(getActivity());
            final View v = inflater.inflate(R.layout.fragment_dialog_edit_date, null);
            mDatePicker = (DatePicker) v.findViewById(R.id.dialog_edit_date);
            return new AlertDialog.Builder(getActivity()).setTitle("Set Date...").setView(v).setCancelable(true).setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Log.d("", "Dialog confirmed");

                    mListener.onDialogPositiveClick(EditDateDialogFragment.this);
                }
            }).setNegativeButton("Abort", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Log.d("", "Dialog abort");
                    mListener.onDialogNegativeClick(EditDateDialogFragment.this);
                    dialog.cancel();
                }
            }).create();
        }
    }

    public class RecordDetailFragment extends SherlockFragment implements EditDateDialogFragment.EditDateDialogListener {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            if (savedInstanceState != null) {
                // Update reference
                        // Update reference
                        EditDateDialogFragment attachedDialogFragment = (EditDateDialogFragment) getActivity().getSupportFragmentManager().findFragmentByTag("EditDateDialogFragment"); // "tag" is the string set as the tag for the dialog when you show it
                if (attachedDialogFragment != null) {
                    // the dialog exists so update its listener
                    attachedDialogFragment.setListener(this);
                }
            }
        }

        // Called somewhere in the fragment
        public void showDialog() {
            EditDateDialogFragment editDateFragment = EditDateDialogFragment.newInstance(recordId);
            editDateFragment.setListener((EditDateDialogListener) this);
            editDateFragment.show(getActivity().getSupportFragmentManager(), "EditDateDialogFragment");
        }

        @Override
        public void onDialogPositiveClick(DialogFragment dialog) {
            Log.d("RecordDetailFragment", "Callback Dialog confirmed");
            int year = ((EditDateDialogFragment) dialog).mDatePicker.getYear();
            Log.d("RecordDetailFragment", "Year of DatePicker: " + year);

        }

        @Override
        public void onDialogNegativeClick(DialogFragment dialog) {
            Log.d("RecordDetailFragment", "Callback Dialog abort");
            // TODO Auto-generated method stub

        }
    }

我不确定为什么在关闭对话框后DatePicker仍然可用。 @Luksprog:你怎么看?你的意思是这样吗?