看了有关这个问题的几篇博文,几乎都是引用了stackoverflow上的一个回答;
问题:
I know that a fragment’s view hierarchy has to be inflated in onCreateView, but what other functionality can be in onCreateView vs. what should wait for onActivityCreated? My current implementation uses separate activities for everything, and a typical activity does most of its work in its onCreate method, including inflating the view, setting the content view, initializing the various widgets with data, setting up listeners, etc.
大概意思就是:哪些代码应该在onCreateView()执行哪些应该在onActivityCreate()中执行;
回答:
If your view is static, then moving any code to the onActivityCreated method is not necessary. But when you - for instance, fill some lists from the adapter, then you should do it in the onActivityCreated method as well as restoring the view state when setRetainInstance used to do so.
Also accessing the view hierarchy of the parent activity must be done in the onActivityCreated, not sooner.
大概意思就是:如果您的View是静态的,那么就没有必要在onActivityCreate()中执行;如果您的View是动态的,比如使用ListView等需要Adapter填充的,View就需要在onActivityCreate()中执行。(静态的View不是指Static View,而是指后期不需要修改的View)
个人理解:
onCreateView():
这个方法就相当于Activity onCreate()方法中的 setContentView()是进行XML视图填充的,这也是为什么setContentView()这个方法几乎要写在onCreate()方法的第一行的原因,因为如果XML视图还没填充,我们就没有办法对每个View进行操作,所以我们在每个Fragment中对每个View进行操作的时候都必须在onCreateView()后面执行。
onActivityCreate():
这个相当于Activity中 onCreate()中 setContentView()这句话后面的代码。
这里可能就有人会想了: 那我完全可以把 对每个View操作的代码放在onCreateView()代码块结尾处写啊,完全没必要分开到onActivityCreate()中写啊,分开写反而让人更容易模糊。
个人理解:
1. 一个是单一原则,能引起一个方法改变的原因只能有一个,onCreateView()只负责视图填充,onActivityCreate()负责对视图修改,如果你的视图不需要修改那就放在onCreateView()中写吧。 当然这个说法不是特别站得住脚。不过还是能帮助记忆的。
最后加上一句刚从stackoverflow上学到的一句话
Don’t think everyone got it, Diffy, but they were just happy with the answer
不要认为每个人都懂了,只是他们对答案满意了
如果您看了这篇博客您觉得我说的对,请您不要以为您懂了,因为这是您对这个答案满意了
---------------------
作者:maxcion
来源:CSDN
原文:https://blog.csdn.net/maxcion/article/details/77906982
版权声明:本文为博主原创文章,转载请附上博文链接!