如何在 Activity 中显示相同的对话框和在不同情况下显示片段?

how to show same Dialog in Activity and Fragment in Different situation?

我正在做一个示例项目,我在其中使用带有 Fragments.When 的导航抽屉 我在 item1 行中单击它会打开对话框 Fragment1 .In Dialog Fragment1 我有一个按钮 .

我的要求是我想打开同一个 Dialog,它是在单击 Fragment 中的按钮时从导航行 item1 触发的... 我正在使用以下代码在 Activity

中创建对话框
    public void showRegisterDialog() {

    final Dialog dialog = new Dialog(MainActivity.this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.custom_dialog_register);
    dialog.show();
}

和以下代码以在 Fragment 中打开对话框

  private void LoadFragmentView(int position) {
    // update the main content by replacing fragments
    Fragment fragment = null;
    switch (position) {
        case 1:
            fragment = new Fragment2();
            showRegisterDialog();
            break;
        case 2:
            fragment = new Fragment3();

            break;
        case 3:
            fragment = new Fragment4();
            break;
        case 4:
            fragment = new Fragment5();
            break;


        default:
            break;
    }
I need some guidelines,thank you..

我做了一些研究并得到了解决方案。 您需要在片段中使用回调方法。 为此,您需要使用以下代码:

your_button_on_fragment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           ((YourActivityName)getActivity()).showRegisterDialog();
        }
    });