为什么我们可以在onActivityCreated之前运行的onCreateView中调用getActivity()? [英] why we can call getActivity() in onCreateView which run before onActivityCreated?

查看:715
本文介绍了为什么我们可以在onActivityCreated之前运行的onCreateView中调用getActivity()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很困惑 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 call getActivity(). Sometimes you cannot get Activity by getActivity(). 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 after onCreateView() though

    Your safest bet for activity existence is:

    这篇关于为什么我们可以在onActivityCreated之前运行的onCreateView中调用getActivity()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆