Reputation: 169
I would like to see DialogFragment after pressing the button, I have two code snippets:
First:
if (view.equals(b1)) {
Fragment2 fr2 = new Fragment2();
fr2.show(manager, "addCity");
}
I don't understand why this tag is in the show () method, since it has no effect on program change.
Second:
Fragment fr = manager.findFragmentByTag("addCity");
if (view.equals(b1)) {
if (fr != null) {
manager.beginTransaction().remove(fr).commit();
}
Fragment2 fr2 = new Fragment2();
fr2.show(manager, "addCity");
}
In the second example, I don't understand what this line of code is for:
Fragment fr = manager.findFragmentByTag("addCity");
Since the reference variable fr will always be null because there is currently no fragment under the name of such a tag.
In addition, why does this condition appear, since just the previous change fr will always be null, so this if will never come true.
if (fr != null) {
manager.beginTransaction().remove(fr).commit();
}
Upvotes: 1
Views: 1098
Reputation: 199795
When you use show(manager, "addCity")
, then second parameter is the tag for the Fragment. By using findFragmentByTag()
with the same tag, you're looking to see if the DialogFragment
already exists and, if it does (fr != null
), then remove it.
This is very defensive code, probably made in an attempt to avoid users very, very quickly double tapping the button. However, because it doesn't use showNow()
(instead of show()
), it actually doesn't do a good job at this because show()
is asynchronous.
In general, you don't need this code at all - just call show()
without any of the ceremony, using whatever tag you want (the tag only matters if you're later trying to use findFragmentByTag()
to retrieve your DialogFragment
after the fact).
But if you do want to be defensive and avoid even the extremely rare chance that the user opens up two dialogs, then you need to
1) Use showNow()
instead of show()
so that the FragmentManager is immediately updated, ensuring that findFragmentByTag()
actually does return the Fragment in that case
2) Instead of removing and then calling show()
again, just don't call show()
if it already being shown - you're just doing extra work.
This would mean your code would look like
if (view.equals(b1)) {
Fragment existingDialog = manager.findFragmentByTag("addCity");
// Only add a new dialog if it isn't already present.
if (existingDialog == null) {
Fragment2 fr2 = new Fragment2();
fr2.showAll(manager, "addCity");
}
}
Upvotes: 5