简体   繁体   中英

Fragments Not getting destroyed on Activity finish

I have notice this strange thing. I have series of fragment which is hosted by an Activity. When activity is killed by pressing back and opened again, all the fragments retain their data and variables. I have read the article on android developers where it is written that the fragments are attached to the hosted activity and is destroyed when the finish of the activity gets called.

How should I deal with this?

The Activity is not diying when you press Back Button. So the Fragments don't die too. onStop() in Activity will be called. The Activity can be destroyed any time if the system lack resourses. Read more about activity lifecycle in Android If you want to kill the Activity, override onBackPressed() like this

@Override
    public void onBackPressed(){
        finish();
    }

This will kill the current Activity and all fragments, attached to it.

You could also deal with this by overriding Fragment's onStart() and onStop() Methods. onStop() gets called when the Activity the Fragment belongs to becomes totally invisible, for example when going to the back stack. onStart() is called when the Activity the Fragment belongs to is becoming visible again.

You could reset your Fragment's UI in Fragment's onStart() Method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM