当前位置:网站首页>About getfragmentmanager () and getchildfragmentmanager ()

About getfragmentmanager () and getchildfragmentmanager ()

2022-07-05 09:36:00 Black Mountain demon 2018

The first time a rookie writes a blog , Let's start with the problems encountered in the project

First, the problem arises

One activity It contains a fragment page , One fragment There are more than one fragment, The technology used is viewpager + fragment, First entry fragment No problem loading , The life cycle is also implemented . Because my project should activity Of launchMode yes singleTask Pattern , When entering this for the second time activity when ,viewpager Inside fragment There is a problem with loading , The life cycle is not implemented .

Problem solving

Later it was found that getFragmentManager() and getChildFragmentManager() The wrong use of the two methods leads to .

Look at the source

/**  * Return the FragmentManager for interacting with fragments associated  * with this fragment's activity. Note that this will be non-null slightly  * before {
    @link #getActivity()}, during the time from when the fragment is  * placed in a {
    @link FragmentTransaction} until it is committed and  * attached to its activity.  *  * <p>If this Fragment is a child of another Fragment, the FragmentManager  * returned here will be the parent's {
    @link #getChildFragmentManager()}.  */ final public FragmentManager getFragmentManager() {
    return mFragmentManager;
}

/**  * Return a private FragmentManager for placing and managing Fragments  * inside of this Fragment.  */ 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;
}
  The source code comments are very clear getFragmentManager() The obtained manager is for fragment Attached to activity Speaking of , That is to say activity Inner management level 1 sub fragment What is used , If fragment There are also fragment, You should use getChildFragmentManager() Method , After modification, the problem is indeed solved .

原网站

版权声明
本文为[Black Mountain demon 2018]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140536454515.html