首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Android Fragment 完整指南:生命週期、通訊與最佳實踐

     編輯:Java 相關知識

Fragment 是 Android 開發中實現 UI 模組化、支援多螢幕適配的核心元件。本文系統整理 Fragment 的建立方式、生命週期、靜態/動態載入、與 Activity 及 Fragment 間通訊機制,並附上實戰程式碼範例。

一、Fragment 基本概念

Fragment 代表 Activity 使用者介面的一部分行為或介面區塊,必須嵌入在 Activity 中運行。每個 Fragment 擁有獨立的 XML 版面配置與生命週期,封裝性優異,便於複用與動態替換。

二、建立 Fragment:版面配置與核心生命週期方法

1. XML 版面配置 (fragment_layout.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/testview" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button" />
</LinearLayout>

2. Java 類別實作與關鍵生命週期回調

public class SampleFragment extends Fragment {

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        // 取得 Activity 參考,建立通訊介面
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 初始化資料、設定 setRetainInstance(true) 等
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 膨脹版面配置,初始化 View 元件
        return inflater.inflate(R.layout.fragment_layout, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Activity onCreate 完成,可安全進行 View 操作與業務邏輯
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 釋放 View 相關資源,防止記憶體洩漏
    }

    @Override
    public void onStart() {
        super.onStart();
        // Fragment 可見
    }
    // 其他回調:onResume, onPause, onStop, onDestroy, onDetach 等
}

三、在 Activity 中載入 Fragment

1. 靜態載入(XML 中宣告)

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <fragment
        android:id="@+id/firstFragment"
        android:name="com.example.FirstFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <fragment
        android:id="@+id/secondFragment"
        android:name="com.example.SecondFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />
</LinearLayout>

注意: 每個 Fragment 必須有唯一識別符(android:id、android:tag 或容器 View ID),以便系統在重建時恢復狀態。

2. 動態載入(FragmentTransaction API)

FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
SampleFragment fragment = new SampleFragment();
ft.add(R.id.fragment_container, fragment, "TAG_SAMPLE");
ft.commit(); // 必須呼叫 commit() 讓變更生效

常用操作:add()、replace()、remove()、hide()/show()、addToBackStack() 支援返回鍵導航。

四、Fragment 與 Activity 通訊三大模式

原則: Fragment 之間不直接通訊,皆透過宿主 Activity 轉發。

模式 1:建構帶參數的 Fragment(推薦)

public class DetailFragment extends Fragment {
    public static DetailFragment newInstance(int index, String title) {
        DetailFragment f = new DetailFragment();
        Bundle args = new Bundle();
        args.putInt("index", index);
        args.putString("title", title);
        f.setArguments(args);
        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int index = getArguments().getInt("index", 0);
        String title = getArguments().getString("title", "");
    }
}

// Activity 中載入
getSupportFragmentManager().beginTransaction()
    .replace(R.id.container, DetailFragment.newInstance(5, "標題"))
    .commit();

模式 2:Activity 持有 Fragment 參考,直接呼叫 public 方法

// Fragment
public void updateContent(String data) { /* ... */ }

// Activity
DetailFragment fragment = (DetailFragment) getSupportFragmentManager()
        .findFragmentById(R.id.detail_fragment);
if (fragment != null) fragment.updateContent("新資料");

模式 3:定義 Listener 介面,Activity 實作(事件回傳)

// Fragment 定義介面
public interface OnItemClickListener {
    void onItemClick(String link);
}
private OnItemClickListener listener;

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnItemClickListener) {
        listener = (OnItemClickListener) context;
    } else {
        throw new ClassCastException("Activity 必須實作 OnItemClickListener");
    }
}

// 觸發事件
public void onItemSelected(View v) {
    listener.onItemClick("https://example.com");
}

// Activity 實作
public class MainActivity extends AppCompatActivity implements DetailFragment.OnItemClickListener {
    @Override
    public void onItemClick(String link) {
        // 處理事件
    }
}

五、最佳實踐提醒

  • 使用 getSupportFragmentManager() 以支援舊版 Android。
  • 避免在 Fragment 建構子中執行耗時操作,改用 onCreate 或 onViewCreated。
  • 妥善處理 onSaveInstanceState 保存暫態資料。
  • 巢狀 Fragment 需使用 getChildFragmentManager()。

熟練掌握 Fragment 機制,是打造模組化、可維護 Android App 的關鍵基石。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved