在UI片段重新创建期间,不再需要在无头片段上调用setTargetFragment吗?

时间:2016-10-30 05:12:41

标签: android android-fragments

使用无头片段技术(带setRetainedInstance(true)的片段)非常常见,让长时间运行的任务处理UI更新。

https://stackoverflow.com/a/12303649/72437

public class UIFragment extends Fragment {
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        headlessFragment = (HeadlessFragment)fm.findFragmentByTag(HEADLESS_FRAGMENT);

        if (headlessFragment == null) {
            // This happens during UIFragment first-time creation.

            headlessFragment = HeadlessFragment.newInstance();
            headlessFragment.setTargetFragment(this, 0);
            fm.beginTransaction().add(headlessFragment , HEADLESS_FRAGMENT).commitAllowingStateLoss();
        } else {

            // UIFragment is having configuration change.
            // UIFragment is being re-created.
            // Make sure headlessFragment is having latest instance of UIFragment.
            headlessFragment.setTargetFragment(this, 0);
        }
    }
}

我正在使用支持库。

许多年前,当UIFragment重新创建时,以下代码段是必不可少的,以确保无头片段引用最新的UIFragment实例。

// UIFragment is having configuration change.
// UIFragment is being re-created.
// Make sure headlessFragment is having latest instance of UIFragment.
headlessFragment.setTargetFragment(this, 0);

然而,今天当我重新测试代码时,使用最新的支持库v7:25.0.0,我意识到这些代码已经不再需要了。我可以在

中写下来
public class UIFragment extends Fragment {
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        headlessFragment = (HeadlessFragment)fm.findFragmentByTag(HEADLESS_FRAGMENT);

        if (headlessFragment == null) {
            // This happens during UIFragment first-time creation.

            headlessFragment = HeadlessFragment.newInstance();
            headlessFragment.setTargetFragment(this, 0);
            fm.beginTransaction().add(headlessFragment , HEADLESS_FRAGMENT).commitAllowingStateLoss();
        } else {
             // UIFragment is being created.
             //
             // Event without calling headlessFragment.setTargetFragment,
             // headlessFragment.getTargetFragment will *magically* 
             // return latest instance of UIFragment.
        }
    }
}

首先,我怀疑,在最新的支持库中,在headlessFragment.setTargetFragment重新创建期间会自动调用UIFragment

但是,当我尝试通过覆盖headlessFragment.setTargetFragment进行一些日志记录来确认时,我意识到在UIFragment重新创建期间没有调用它。

我可以知道,headlessFragment如何能够获得最新重新创建的UIFragment神奇地

0 个答案:

没有答案