上一篇介紹了 Fragment 基礎,本文深入實戰核心:FragmentManager 管理、FragmentTransaction 動態增刪替換、回退棧導航、與 Activity 雙向通訊,並說明官方 API Demos 範例位置。
透過 getFragmentManager() (或 getSupportFragmentManager()) 取得實例,核心能力:
findFragmentById(R.id.container) (靜態 XML 宣告)、findFragmentByTag("tag") (動態新增時指定 tag)。popBackStack() 模擬返回鍵、popBackStackImmediate() 同步彈出、addOnBackStackChangedListener() 監聽棧變化(可同步 Toolbar 標題、BottomNavigation 狀態)。beginTransaction() 回傳 FragmentTransaction。每次 UI 變更(增/刪/替換/隱藏/顯示)構成一個事務,必須 commit() 才生效。
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.container, newFragment, "tag"); // 新增
ft.remove(fragment); // 移除 (若未加入 backStack 會銷毀)
ft.replace(R.id.container, newFragment, "tag"); // 替換 = remove + add
ft.hide(fragment); // 隱藏 (保留狀態、View 隱藏)
ft.show(fragment); // 顯示
ft.attach(fragment); // 重新附加 (onCreateView 再次呼叫)
ft.detach(fragment); // 分離 (View 銷毀、實例保留)
// 動畫
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left);
// 回退棧
ft.addToBackStack("optional_tag"); // 可選 tag,供 popBackStack("tag", 0) 精確彈出
ft.commit(); // 非同步排程
// ft.commitNow(); // 同步執行 (API 24+)
// ft.commitAllowingStateLoss(); // 允許狀態丟失 (需謹慎使用)
public void showDetailFragment(DetailFragment fragment) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, fragment, "detail");
ft.addToBackStack(null); // 允許返回列表
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
commit() 必須是最後呼叫。add() 時,後加入的在上層 (Z-order)。onSaveInstanceState() 後呼叫 commit() 會拋 IllegalStateException。解決:用 commitAllowingStateLoss() 或在 onResumeFragments() 之後觸發。// 1. 直接取得 Activity (需注意生命週期,避免 NPE)
((MainActivity) requireActivity()).onItemSelected(item);
// 2. 推薦:定義介面回呼 (解耦)
public interface OnItemSelectedListener {
void onItemSelected(Item item);
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof OnItemSelectedListener) {
listener = (OnItemSelectedListener) context;
} else {
throw new RuntimeException(context + " must implement OnItemSelectedListener");
}
}
@Override
public void onDetach() {
super.onDetach();
listener = null; // 避免洩漏
}
// 1. 透過 ID/Tag 找到 Fragment 實例
DetailFragment fragment = (DetailFragment) getSupportFragmentManager()
.findFragmentById(R.id.fragment_container);
// 或 findFragmentByTag("detail")
// 2. 直接呼叫 public 方法
if (fragment != null) {
fragment.updateData(newData);
}
避免直接持有彼此引用,改用 ViewModel (Scoped to Activity) 共享資料:
// SharedViewModel.kt
class SharedViewModel : ViewModel() {
val selectedItem = MutableLiveData- ()
}
// Fragment A
viewModel.selectedItem.observe(viewLifecycleOwner) { item -> /* 更新 UI */ }
// Fragment B
viewModel.selectedItem.value = newItem
優點:生命週期感知、配置變更倖存、零耦合、易測試。
SDK 安裝目錄下:<sdk>/samples/android-<api_level>/ApiDemos/,專案模組名通常為 ApiDemos。關鍵 Fragment 範例類別:
FragmentCustomAnimations:自訂動畫切換FragmentStack:回退棧管理FragmentArguments:傳遞參數 (setArguments/Bundle)FragmentDialog:DialogFragment 用法FragmentMenu:Fragment 選單整合FragmentRetainInstance:setRetainInstance(true) 保留實例 (現代用 ViewModel 替代)熟練掌握 FragmentTransaction 的增刪替換/隱藏顯示/動畫/回退棧控制、Fragment 與 Activity 的介面回呼與 ViewModel 共享資料模式,是構建複雜單 Activity 多 Fragment 架構 (如 BottomNavigation + ViewPager、抽屜導航、多步驟表單) 的基石。善用官方 API Demos 並遷移至 AndroidX Fragment + Jetpack Navigation,可大幅降低導航邏輯複雜度。