Search code examples
dialogandroid-dialogfragmentandroid-dialog

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


I am doing a sample Project where I am using Navigation Drawer with Fragments.When I click in row item1 it opens Dialog Fragment1 .In Dialog Fragment1 I have a button .

My requirement is I want to open same Dialog which is triggred from navigation row item1 when button in Fragment is clicked ... I am using Following code to make Dialog in 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();
}

and following code to open Dialog in 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..

Solution

  • I did some research and got the solution. You need to use callback method in fragment. For this purpose,you need to use the following codes:

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