Very simple code, but got error “Activity has been destroyed” when use Fragment

前端 未结 9 1156
误落风尘
误落风尘 2020-12-05 14:15

I made a very simple Activity which shows a simple ListFragment like below:

My Activity:

public class MyActivity ex         


        
9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-05 15:04

    To give an explanation:

    The framework creates the Activity and calls Activity.onCreate().

    Activity.onCreate() will somehow attach to the FragmentManager to let it know about the hosting activity. Activity.onDestroy() will unregister it again.

    Now, you extend Activity and override onCreate(). You make calls to FragmentManager without calling through toActivity.onCreate(). The whole registration logic explained above is not executed. The FragmentManager therefore does not know anything about the activity and assumes it has already been destroyed and generates the exception with the misleading error message.

提交回复
热议问题