为什么我们可以在onActivityCreated之前运行的onCreateView中调用getActivity()? [英] why we can call getActivity() in onCreateView which run before onActivityCreated?
问题描述
我真的很困惑 Fragment
生命周期,特别是在调用 getActivity()
时。有时你不能通过 getActivity()
获取 Activity
。它总是会引起一些令人困惑的bug。
谢谢任何人都可以解决这个难题。
getActivity()
在你的片段正在准备过程中并准备就绪时可以为null。
循环绑定回调方法。这些方法将在片段正在准备时在某个时间被调用。
- Fragment.onActivityCreated(Bundle)是片段活动不会为空的地方,即
getActivity()
将是一个有效的实例。它发生在onCreateView()
尽管
/ b>
您对活动存在最安全的赌注是:
I really get confused with
Fragment
lifecycle, especially for the time to callgetActivity()
. Sometimes you cannot getActivity
bygetActivity()
. And it always caused some puzzling bugs.
Thank you for anyone can solve the puzzle.解决方案getActivity()
can be null while your fragment is in process of preparation and about to be ready.The fragment life cycle is bound to callback methods. These method will be called somewhere in time while fragment is preparing.
- Fragment.onActivityCreated(Bundle) is the place when the fragment activity will not be null, i.e.
getActivity()
will be a valid instance. It happens afteronCreateView()
though
Your safest bet for activity existence is:
这篇关于为什么我们可以在onActivityCreated之前运行的onCreateView中调用getActivity()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Fragment.onActivityCreated(Bundle) is the place when the fragment activity will not be null, i.e.