最佳答案
问题: 如何创建从 Dialog片段到另一个片段的回调。在我的例子中,所涉及的活动应该完全不知道 Dialog片段。
我考虑过了
public class MyFragment extends Fragment implements OnClickListener
然后在某个时候,我 可以做
DialogFragment dialogFrag = MyDialogFragment.newInstance(this);
dialogFrag.show(getFragmentManager, null);
我的对话框片段是什么样子的
protected OnClickListener listener;
public static DialogFragment newInstance(OnClickListener listener) {
DialogFragment fragment = new DialogFragment();
fragment.listener = listener;
return fragment;
}
但是,如果 DialogFragment 在其生命周期中暂停并继续运行,并不能保证侦听器就在附近。片段中唯一的保证是那些通过 setArguments 和 getArguments 通过 Bundle 传递的保证。
如果活动应该是侦听器,那么有一种方法可以引用该活动:
public Dialog onCreateDialog(Bundle bundle) {
OnClickListener listener = (OnClickListener) getActivity();
....
return new AlertDialog.Builder(getActivity())
........
.setAdapter(adapter, listener)
.create();
}
但是我不希望活动监听事件,我需要一个片段。实际上,它可以是任何实现 OnClickListener 的 Java 对象。
考虑一个片段的具体示例,该片段通过 DialogFragment 呈现 AlertDialog。它有是/否按钮。我怎样才能将这些按钮发送回创建它的碎片?