5

我尝试从DialogFragment. 有一个很好的例子,但他们不会DialogFragmentFragment. http://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)中的公共 void ,因为我创建了from a而不是 an ? 如何解决这个问题? EditDateDialogFragmentDialogFragmentFragmentActivity

更新:在 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

4 回答 4

10

刚跳进同样的问题,解决方法很简单。而不是覆盖

public void onAttach(Context context) {}

覆盖这个:

public void onAttach(Activity activity) {}

现在一切都很好DialogFragment

于 2016-05-14T15:46:13.723 回答
9

如何解决这个问题?

我猜你希望RecordDetailFragment实例表现得像EditDateDialogListener. DialogFragment如果是,那么您需要将其显式设置(并更新)作为侦听器:

DialogFragment editDateFragment = EditDateDialogFragment.newInstance( recordId );
editDataFragment.setListener(RecordDetailFragment.this);
editDateFragment.show(getActivity().getSupportFragmentManager(), "EditDateDialogFrame");

像这样setListener()的方法在哪里:EditDialogFragment

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

例如,当用户旋转手机时,将重新创建 Activity 及其片段,您需要重新设置侦听器以指向新创建的RecordDetailFragment实例(您可能需要使用WeakReferencefor mListener)。您可以在此答案中找到类似的内容(您将在 中查找两个片段onCreate)。

编辑:在onCreate方法中Activity

if (savedInstanceState != null) {
    RecordDetailFragment df = (RecordDetailFragment) getSupportFragmentManager().findFragmentByTag("rdf"); // "rdf" is the tag used when you add the RecordDetailFragment to the activity
    EditDateDialogFragment s = (EditDateDialogFragment) getSupportFragmentManager().findFragmentByTag("tag"); // "tag" is the string set as the tag for the dialog when you show it
    if (s != null) {
                   // the dialog exists so update its listener
        s.setListener(df);
    }
}
于 2012-12-28T14:12:45.190 回答
3

在 onCreateDialog 的某处将 mListener 转换为 getActivity():

try {
    mListener = (EditDateDialogListener) getActivity();
} catch (Exception e) {
    throw new ClassCastException(getActivity().toString()
            + " must implement EditDateDialogListener");
}
于 2017-06-16T09:15:30.000 回答
0

一种更“现代”的方法是使用新的Fragment Result API

在片段 A(父)onCreate 上添加结果侦听器:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    childFragmentManager.setFragmentResultListener("requestKey", this) { key, bundle ->
        val result = bundle.getString("bundleKey")
    }

}

无论您需要,在子片段 B 上设置结果(例如,在按钮单击侦听器上):

button.setOnClickListener {
    val result = "resultSample"

    setFragmentResult("requestKey", bundleOf("bundleKey" to result))
}

有关文档的更多信息:https ://developer.android.com/guide/fragments/communicate#kotlin

于 2021-10-18T20:11:53.380 回答