android – Find a reference to AppCompatDialogFragment-ThrowExceptions

Exception or error:

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();, 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 solve:

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, "dialog");

And then you can retrieve the fragment:

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

Leave a Reply

Your email address will not be published. Required fields are marked *