2012-08-09 59 views
13

我正在使用支持包v4。通过标记找不到片段

mFragmentManager = getSupportFragmentManager(); 

FragmentTransaction ft = mFragmentManager.beginTransaction(); 
ft.add(R.id.fragContainer1, new ModelListFragment(), FRAG_MODEL_LIST); 
ft.add(R.id.fragContainer2, new TrimListFragment(), FRAG_TRIM_LIST); 
ft.commit(); 

Fragment fragment = mFragmentManager.findFragmentByTag(
      MainActivity.FRAG_MODEL_LIST); 
Log.d("MY", "found fragment: " + (fragment != null)); 

总是返回“found fragment:false”。我错过了一些非常明显的东西,它是什么?

回答

15

正如你可以看到doc

的承诺并不会立即发生;它将被安排在主线程上的工作 下一次线程准备就绪完成。

这就是为什么你在commit()之后没有看到你的片段。

+14

如果您真的想要应用事务,请使用[executePendingTransactions](http://developer.android.com/reference/android/app/FragmentManager.html#executePendingTransactions()) – 2012-08-09 13:12:45