1

I am going over the official Android tutorial for DialogFragments. The part that slightly confuses me is:

void showDialog() {
    mStackLevel++;

    // DialogFragment.show() will take care of adding the fragment
    // in a transaction.  We also want to remove any currently showing
    // dialog, so make our own transaction and take care of that here.
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    Fragment prev = getFragmentManager().findFragmentByTag("dialog");
    if (prev != null) {
        ft.remove(prev);
    }
    ft.addToBackStack(null);

    // Create and show the dialog.
    DialogFragment newFragment = MyDialogFragment.newInstance(mStackLevel);
    newFragment.show(ft, "dialog");
}  

So my confusion arises from the fact that they are using findFragmentByTag("dialog"). Nowhere is a layout XML declared that has a tag named dialog in it. In case of normal Fragmants, there are <fragment ../> tags in the layout so I can retrieve fragments with Id or tagname. Here, there isn't any.

So, what gives ? How does this work ?
Also, what if I have multiple DialogFragments ? findFragmentByTag("dialog"); will return what??

:)

1
  • Also, how do I make this work with a support DialogFragment? Commented Aug 3, 2013 at 7:10

1 Answer 1

3

Fragments can be attached to an Activity in two ways: statically by declaring it in the layout xml using the <fragment> tag; or programmatically using FragmentManager and FragmentTransaction. In the case of DialogFragments, you will always be using the latter.

When you attach a fragment to the Activity, such as by using DialogFragment.show(), you can give it a tag. The FragmentManager can then later find this fragment by its tag. In this case, the code is checking if the FragmentManager already has a fragment with this tag (which I believe would be the case if the dialog was already showing when showDialog() was called). If so, it removes the fragment (dismissing the dialog) before showing a new instance of it.

Sign up to request clarification or add additional context in comments.

2 Comments

So, this 'tag' is more like a key-value pair rather than an XML tag
You could think of it that way.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.