FragmentManage:
FragmentManager能夠實現管理activity中fragment. 通過調用activity的getFragmentManager()取得它的實例.
1、使用findFragmentById() (用於在activity layout中提供一個UI的fragment)或findFragmentByTag()(適用於有或沒有UI的fragment)獲取activity中存在的fragment2、將fragment從後臺堆棧中彈出, 使用 popBackStack() (模擬用戶按下BACK 命令).3、使用addOnBackStackChangeListener()註冊一個監聽後臺堆棧變化的listener.
FragmentTransaction:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container,newFragment);
transaction.addToBackStack(null); // Commit the transaction
transaction.commit();
- 必須最後調用 commit().
- 如果添加多個fragment到同一個容器, 那麼添加的順序決定了它們在view hierarchy中顯示的順序.