Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way of dismissing DialogFragment while application is in background

I started using DialogFragment, because they are working nicely through orientation changes, and stuff. But there is nasty problem I encountered.

I have AsyncTask that shows progress DialogFragment and dismisses it onPostExecute. Everything works fine, except when onPostExecute happens while application is in background (after pressing Home button, for example). Then I got this error on DialogFragment dismissing - "Can not perform this action after onSaveInstanceState". Doh. Regular dialogs works just fine. But not FragmentDialog.

So I wonder, what is the proper way of dismissing DialogFragment while application is in background? I haven't really worked with Fragments a lot, so I think that I'm just missing something.

like image 709
Sver Avatar asked Feb 17 '12 08:02

Sver


People also ask

How do you dismiss a DialogFragment?

tl;dr: The correct way to close a DialogFragment is to use dismiss() directly on the DialogFragment. Control of the dialog (deciding when to show, hide, dismiss it) should be done through the API here, not with direct calls on the dialog.

How do I know if DialogFragment is showing?

that should mean its in the foreground displaying if im not mistaken. If you call DialogFragment's creation several times in one moment, dialogFragment = getSupportFragmentManager(). findFragmentByTag("dialog"); will return null, and all dialogs will be shown.

How do you pass arguments to DialogFragment?

you can set your args. class IntervModifFragment : DialogFragment(), ModContract. View { companion object { fun newInstance( plom:String,type:String,position: Int):IntervModifFragment { val fragment =IntervModifFragment() val args = Bundle() args. putString( "1",plom) args.

Is DialogFragment deprecated?

This class was deprecated in API level 28. Use the Support Library DialogFragment for consistent behavior across all devices and access to Lifecycle.


2 Answers

DialogFragment has a method called dismissAllowingStateLoss()

like image 119
Jiang Qi Avatar answered Sep 19 '22 17:09

Jiang Qi


This is what I did (df == dialogFragment):

Make sure that you call the dialog this way:

df.show(getFragmentManager(), "DialogFragment_FLAG"); 

When you want to dismis the dialog make this check:

if (df.isResumed()){   df.dismiss(); } return; 

Make sure that you have the following in the onResume() method of your fragment (not df)

@Override public void onResume(){   Fragment f = getFragmentManager().findFragmentByTag("DialogFragment_FLAG");   if (f != null) {     DialogFragment df = (DialogFragment) f;     df.dismiss();   }   super.onResume(); }    

This way, the dialog will be dismissed if it's visible.. if not visible the dialog is going to be dismisded next the fragment becomes visible (onResume)...

like image 25
Mohammed Aljarrah Avatar answered Sep 22 '22 17:09

Mohammed Aljarrah