简体   繁体   English

当附加在活动的xml中时,Android Fragment生命周期

[英]Android Fragment lifecycle when attached in activity's xml

Fragment's onCreate, onCreateView is called before Actvity's onCreate, when it is declared in activity XML layout. 在活动XML布局中声明片段时,在Actvity的onCreate之前调用Fragment的onCreate,onCreateView。

Is it is normal? 这是正常的吗? Can I develop code based on above life-cycle. 我可以根据上述生命周期开发代码吗?

//Fragment declared in activity xml
<fragment android:name="screenfragments.SearchableFragment"
        android:id="@+id/searchable_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

Thanks 谢谢

Yes, you can have what you have. 是的,您可以拥有所拥有的。 But keep in mind that when you declare the fragment in the xml layout the fragment will always be present and you cannot remove it or replace it dynamically. 但是请记住,当您在xml布局中声明该片段时,该片段将始终存在,并且您无法将其删除或动态替换。

This is somewhat contrary to the purpose of fragments which were designed to be reusable components not tied to the Activity. 这有点违背了片段的目的,这些片段被设计为可重用的组件,与活动无关。 In the case that you have mentioned, the Fragment is tied to the Activity. 在您提到的情况下,片段与活动相关。

To conclude, the design principle that you are using is not normal but it will work and you can design around it. 总而言之,您使用的设计原理并不正常,但可以正常工作,您可以围绕它进行设计。

This odd ordering of lifecycle events is a result of your fragment being declared in the activity's XML instead of in code. 生命周期事件的这种奇怪排序是由于您的片段在活动的XML中而不是在代码中声明的结果。 You can create the fragment and add it to the activity in the onCreateView step of the activity so you can ensure that the fragment's onCreate is called after the activity's. 您可以在活动的onCreateView步骤中创建片段并将其添加到活动中,以便确保在活动之后调用片段的onCreate。

See: http://developer.android.com/training/basics/fragments/fragment-ui.html#AddAtRuntime 请参阅: http : //developer.android.com/training/basics/fragments/fragment-ui.html#AddAtRuntime

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM