0

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

@Override
protected void onCreate(Bundle savedState)
  {
  super.onCreate(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?

Leszek
  • 1,181
  • 1
  • 10
  • 21
  • `savedState` won't be `null` ...so why it should be recreated?? – Martin Zeitler Feb 18 '20 at 00:20
  • @MartinZeitler - fragments are automatically saved and restored. The `savedState==null` is necessary to ensure that it only is created once. – ianhanniballake Feb 18 '20 at 00:28
  • @ianhanniballake `onConfigurationChange()` it still won't enter that branch, because it won't be `null` then. Looking it up by tag-name appears solid, because it doesn't add any clutter, even when it is only a local variable. It might indeed be a difference, if it's about 1 dialog or about multiple ones, if keeping a reference to the instance or using fragment-tags suits better. – Martin Zeitler Feb 18 '20 at 00:57
  • @MartinZeitler - you won't go through `onCreate()` at all if you're handling configuration changes manually. You'll *always* need to look up references to your fragments from FragmentManager since they'll *always* be recreated along with the activity - that's precisely what the `tag` is for. Really the only factor is whether you do that lookup in an `else` block for when `savedState != null` or if you do it on demand. In either case, it'll be the same code to find the fragment. – ianhanniballake Feb 18 '20 at 01:01
  • @ianhanniballake Does that mean, that an reference to the dialog's instance may change on `onConfigurationChange()`? If so, then looking up by tag-name seems to be the only possible solution. – Martin Zeitler Feb 18 '20 at 01:19

1 Answers1

2

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");
ianhanniballake
  • 191,609
  • 30
  • 470
  • 443