Android getFragmentByTag在重新创建时返回null

时间:2014-05-27 15:33:43

标签: java android android-fragments

我正在尝试检索配置更改的片段(如屏幕旋转)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_all_tasks);

    // Create/retain AllTasksFragment
    FragmentManager fragmentManager = this.getFragmentManager();
    fragmentManager.executePendingTransactions();       
    allTasksFragment = (AllTasksFragment) fragmentManager.findFragmentByTag(TAG_ALL_TASKS_FRAGMENT);
    if (allTasksFragment == null)
    {
        allTasksFragment = new AllTasksFragment();
        allTasksFragment.setRetainInstance(true);
        fragmentManager.beginTransaction().add(R.id.container, allTasksFragment, TAG_ALL_TASKS_FRAGMENT).commit();
        fragmentManager.executePendingTransactions();
        Fragment fragment = fragmentManager.findFragmentByTag(TAG_ALL_TASKS_FRAGMENT);
    }
}

在这段代码中,if子句中的findFragmentByTag正常工作(使用eclipse调试器测试),但第一个总是返回null。我做错了什么?

0 个答案:

没有答案