Fragment在xml中但作用不是显示view

时间:2024-04-26 11:30:29

2013-12-17

有时候会发现在xml文件中有使用fragment,但是却不是为了显示View,代码如下:

 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AnimTest" > <fragment
android:id="@+id/loader_fra"
class="com.example.sdtest.LoadInXmlFragment"
android:layout_height="0dip"
android:layout_width="0dip"
android:visibility="gone"/> <ImageView
android:id="@+id/welcome_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/phone"
tools:ignore="ContentDescription" /> </FrameLayout>

可以看到上面xml文件中有LoadInXmlFragment,那我们来看看当进入和退出Activity时Activity和LoadInXmlFragment的生命周期, log如下:

 // Enter Activity:
D/David-Activity( 7378): onCreate
D/David-Fragment( 7378): onAttach
D/David-Activity( 7378): onAttachFragment
D/David-Fragment( 7378): onCreate
D/David-Fragment( 7378): onCreateView
D/David-Fragment( 7378): onActivityCreated
D/David-Activity( 7378): onStart
D/David-Fragment( 7378): onStart
D/David-Activity( 7378): onResume
D/David-Fragment( 7378): onResume
// Exist Activity:
D/David-Fragment( 7378): onPause
D/David-Activity( 7378): onPause
D/David-Fragment( 7378): onStop
D/David-Activity( 7378): onStop
D/David-Fragment( 7378): onDestroy
D/David-Activity( 7378): onDestroy
D/David-Fragment表示LoadInXmlFragment中打印的log;
D/David-Activity表示Activity中打印的log;
可以看到Fragment基本是随着Activity执行自己的生命周期函数,因此这样使用Fragment的好处是:
1. 由于Fragment的上面周期和Activity保持一致,因此可以利用其完整的生命周期,将某些需要在Activity特定生命周期中执行的操作放在Fragment里面;
2. 保证较好的编码风格;
3. 目前就想到这么多,希望大家补充;

这种方式在Phonebook应用中很常见。