Home » Android » android – Find a reference to AppCompatDialogFragment-Exceptionshub

android – Find a reference to AppCompatDialogFragment-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment


In my Andriod app, I’ve got a Dialog extended from AppCompatDialogFragment. I show it immediatelly in my App’s main Activity’s onCreate:

protected void onCreate(Bundle savedState)

  // ....

  if( savedState==null )
    MyDialog diag = new MyDialog();
    diag.show(getSupportFragmentManager(), null);

later on I want to dismiss this dialog – so I need to find it. I cannot simply remember a reference to it in my Activity, as when I e.g. rotate the phone the Dialog gets recreated and my reference would be invalid.

How do I get a reference to MyDialog later on in my code?

How to&Answers:

The second parameter to show() is the tag.

This tag is what allows you to use findFragmentByTag() later to retrieve that Fragment.

Therefore, just use any other value than null

diag.show(getSupportFragmentManager(), "dialog");

And then you can retrieve the fragment:

MyDialog diag = (MyDialog) getSupportFragmentManager().findFragmentByTag("dialog");