注意: 原始內容為空。Fragment 是 Android UI 組件化的核心,支援彈性佈局、生命週期獨立、回棧管理。本文系統整理 Fragment 生命週期、FragmentManager 事務操作、ViewBinding 整合、嵌套 Fragment 坑位、與現代 Navigation Component 遷移路徑。
onAttach(Context) → onCreate(Bundle) → onCreateView(LayoutInflater, ViewGroup, Bundle) → onViewCreated(View, Bundle)
→ onStart() → onResume() ←── 可見/可互動
← onPause() ← onStop() ←── 不可見
← onDestroyView() ←── View 銷毀 (但 Fragment 實例存活)
← onDestroy() ← onDetach() ←── 徹底銷毀
onDestroyView() 會在 onDestroy() 前調用,**ViewBinding/資源必須在 onDestroyView 釋放**,否則洩漏。ViewModel 替代。// 獲取 FragmentManager
FragmentManager fm = getSupportFragmentManager(); // Activity
// 或 getChildFragmentManager() 嵌套 Fragment
// 或 getParentFragmentManager() 父 Fragment
// 事務操作
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.container, new HomeFragment(), "HOME_TAG");
ft.replace(R.id.container, new DetailFragment(), "DETAIL_TAG");
ft.addToBackStack("detail"); // 加入回棧,返回鍵可回退
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); // 動畫
ft.setReorderingAllowed(true); // 優化動畫順序 (API 26+)
ft.commit(); // 非同步提交,排程執行
ft.commitNow(); // 同步執行 (需在主執行緒,謹慎使用)
// build.gradle
android { buildFeatures { viewBinding = true } }
// Fragment
private FragmentHomeBinding binding;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
binding = FragmentHomeBinding.inflate(inflater, container, false);
return binding.getRoot();
}
@Override
public void onDestroyView() {
super.onDestroyView();
binding = null; // 關鍵:釋放 View 引用,避免洩漏
}
| 坑位 | 現象 | 解決 |
|---|---|---|
| 使用錯誤的 FragmentManager | 嵌套 Fragment 不顯示、回棧錯亂 | 子 Fragment 必須用 getChildFragmentManager(),父 Fragment 用 getParentFragmentManager() |
| ViewPager + Fragment 狀態丟失 | 頁面切換後資料重置 | 使用 FragmentStateAdapter (ViewPager2) 而非 FragmentPagerAdapter,並正確實作 saveState() |
| 嵌套 Fragment 事務在父 Fragment onSaveInstanceState 後提交 | IllegalStateException: Can not perform this action after onSaveInstanceState | 使用 commitAllowingStateLoss() 或延遲至 onResume() 後提交 |
| DialogFragment 顯示異常 | 嵌套在 Fragment 中 show() 失敗 | 使用 getChildFragmentManager() 而非 getFragmentManager() |
// 共享 ViewModel (Activity 級作用域)
class SharedViewModel : ViewModel() {
val selectedItem = MutableLiveData- ()
}
// Fragment A (列表)
viewModel.selectedItem.observe(viewLifecycleOwner) { item ->
// 更新 UI
}
// Fragment B (詳情)
viewModel.selectedItem.value = selectedItem // 發送事件
優點: 視覺化圖表、型別安全導航、Deep Link 支援、預設動畫、Safe Args 傳參、回棧自動管理。
// build.gradle (project)
dependencies { classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.7.6" }
// build.gradle (app)
plugins { id "androidx.navigation.safeargs.kotlin" }
dependencies {
implementation "androidx.navigation:navigation-fragment-ktx:2.7.6"
implementation "androidx.navigation:navigation-ui-ktx:2.7.6"
}
<navigation xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
android:id="@+id/nav_graph"
app:startDestination="@id/homeFragment">
<fragment
android:id="@+id/homeFragment"
android:name="com.example.HomeFragment"
android:label="Home">
<action
android:id="@+id/action_home_to_detail"
app:destination="@id/detailFragment" />
</fragment>
<fragment
android:id="@+id/detailFragment"
android:name="com.example.DetailFragment"
android:label="Detail">
<argument android:name="itemId" app:argType="long" />
</fragment>
</navigation>
<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:navGraph="@navigation/nav_graph"
app:defaultNavHost="true" />
// Fragment 中導航
val action = HomeFragmentDirections.actionHomeToDetail(itemId = 123L)
findNavController().navigate(action)
// 接收參數 (Safe Args 生成的 Directions/Args 類)
val args = DetailFragmentArgs.fromBundle(requireArguments())
val itemId = args.itemId
viewBinding,onDestroyView 設 binding=null。ViewModel (Activity/Navigation Graph Scope),不直接持有 Fragment 引用。setReorderingAllowed(true),加入回棧用 addToBackStack。getChildFragmentManager()。FragmentTransaction。show(childFragmentManager, tag)。