简体   繁体   中英

What can be stored as member variables for Android fragments without worrying about them being freed up?

I'm just starting out with Android development and I'm noticing that certain references stored as member variables in fragments get freed up by Android if I leave the app (without shutting it down) and then coming back after a while. One example is references to activity action bar.

Is it generally acceptable to store references to things like views, adapters, action bar as member variables or should the references be queried fresh each time they are needed?

What the user perceives as the same instance of an activity or fragment may not actually be the same instance. The Android framework may destroy it whenever it goes into the background or backstack. Activities and fragments both have methods called onSaveInstanceState that you can override to save values that will be passed back to the recreated instance.

As haike00 noted in a comment, you should avoid saving references to fragments, activities, or views this way because those components may themselves be destroyed and recreated, and you would then be leaking the old instances.

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