【发布时间】:2015-09-23 01:05:08
【问题描述】:
我真的对Fragmentlifecycle 感到困惑,尤其是在打电话给getActivity() 的时候。有时您无法通过getActivity() 获得Activity。而且它总是会引起一些令人费解的错误。
感谢任何人都可以解决这个难题。
【问题讨论】:
-
请提供相关代码示例!
-
来自Fragments documentation:
Caution: If you need a Context object within your Fragment, you can call getActivity(). However, be careful to call getActivity() only when the fragment is attached to an activity. When the fragment is not yet attached, or was detached during the end of its lifecycle, getActivity() will return null.。所以应该从onAttach调用。 -
@EricMartinez 我认为这不是对文档的正确解释。我的理解是,由于在调用 onAttach() 时片段与活动相关联,因此它也必须可用于以下生命周期方法,如 onCreate() 和 onCreateView(),即使在 onActivityCreated 之前调用它们会令人困惑()。无论如何,我不记得在 onCreateView() 中调用 getActivity() 时会得到 null,而我编写的所有 Android 应用程序都做到了。
标签: android fragment lifecycle