使用Fragment需要熟悉幾個類,包括FragmentActivity、FragmentManager、 FragmentTranscation,一個FragmentActivity可以包含多個Fragment,誰來管理?
FragmentManager就起到了作用。做Fragment的增加、刪除、替換的時候,事務FragmentTranslation 來負責執行。
getFragmentManager()和getSupportFragmentManager()的區別很容易理解,android的v4擴充套件包中的FragmentActivity中獲取FragmentManager使用的就是getSupportFragmentManager(),android.app中獲取管理類的方法就是getFragmentManager()。
複製程式碼
getChildFragmentManager() 屬於 android.support.v4.app.Fragment
/**
* Return a private FragmentManager for placing and managing Fragments
* inside of this Fragment.
*/
@NonNull
final public FragmentManager getChildFragmentManager() {
if (mChildFragmentManager == null) {
instantiateChildFragmentManager();
if (mState >= RESUMED) {
mChildFragmentManager.dispatchResume();
} else if (mState >= STARTED) {
mChildFragmentManager.dispatchStart();
} else if (mState >= ACTIVITY_CREATED) {
mChildFragmentManager.dispatchActivityCreated();
} else if (mState >= CREATED) {
mChildFragmentManager.dispatchCreate();
}
}
return mChildFragmentManager;
}
複製程式碼
getFragmentManager()在Activity中也在 android.support.v4.app.Fragment
public FragmentManager getFragmentManager() {
return mFragments.getFragmentManager();
}
// android.support.v4.app.Fragment 中
@Nullable
final public FragmentManager getFragmentManager() {
return mFragmentManager;
}
複製程式碼
getSupportFragmentManager() 在 android.support.v4.app.FragmentActivity
/**
* Return the FragmentManager for interacting with fragments associated
* with this activity.
*/
public FragmentManager getSupportFragmentManager() {
return mFragments.getSupportFragmentManager();
}
複製程式碼