Retained Fragments with UI and memory leaks

后端 未结 5 1394
刺人心
刺人心 2020-12-02 05:06

I\'ve read that setting .setOnRetainInstance(true) on fragments presenting UI may lead to memory leaks.

Could somebody please explain why and how this

5条回答
  •  广开言路
    2020-12-02 05:40

    The "setRetainInstance" is used to maintain the state of the fragment when the activity is recreated. According to the official documentation: if we use "setRetainInstance", 2 methods of the fragment's lifecycle will not be executed (onCreate, onDestroy). However, the views contained in the fragment will be recreated, and that is because the lifecycle will be executed from the "onCreateView". In these cases, if we have saved some data in "onSaveInstanceState", we should ask for it in the "onActivityCreated" instead of in the "onCreate".

    Oficial info: https://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean)

    More info: https://inthecheesefactory.com/blog/fragment-state-saving-best-practices/en

提交回复
热议问题