问题
I still have a problem due to a DialogFragment
used on my main activity.
I am currently using this code to remove it:
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Fragment frag = getFragmentManager().findFragmentByTag("LockDialog");
if(frag != null) {
transaction.remove(frag);
transaction.commit();
}
The problem is that I am still getting crashes due to the fact that the dialog has duplicates (meaning the dialog was not properly removed sometimes).
So my question is: is it a right way to remove a DialogFragment
or must it be only used only for Fragments
?
Do I have to use the dismiss()
method all the time?:
Fragment lockFragment = getFragmentManager().findFragmentByTag("LockDialog");
//If the dialog already exist, we dismiss it
if(lockFragment != null && lockFragment instanceof LockDialogFragment) {
LockDialogFragment lockDialog = (LockDialogFragment) lockFragment;
lockDialog.dismiss();
}
This is currently my biggest bug on one of my apps so I want to be sure before choosing one or the other.
Thanks!
EDIT: I just realized my current problem is maybe due to the fact that commits can be delayed, I will add executePendingTransactions
to see if it gets any better.
But still it brings another question, is it necessary to call transaction.remove() if the dialog has been dismissed? Is using dismiss()
more straightforward and safe than using the transactions?
回答1:
DialogFragment.dismiss()
is the correct way. From the documentation:
Dismiss the fragment and its dialog. If the fragment was added to the back stack, all back stack state up to and including this entry will be popped. Otherwise, a new transaction will be committed to remove the fragment.
回答2:
You can use dialogFragment.show(transition,FocusDialogFragment.TAG); instead
and dismiss by dialogFragment.dismiss();
来源:https://stackoverflow.com/questions/23967068/correct-way-to-remove-a-dialogfragment-dismiss-or-transaction-remove