Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Fragment 入門:在同一 Activity 中動態切換界面

編輯:關於 Android 開發

Fragment 的核心用途是在一個 Activity 內部切換界面——切換時只替換 Fragment 容器裡的內容,Activity 本身保持不變。它的生命週期方法與 Activity 基本一致,可以粗略理解為「一個可以被隨時替換的 Activity」。

一、基本用法

第一步,定義布局文件作為 Fragment 的顯示內容:

第二步,編寫 Fragment 類,在 onCreateView() 中加載布局並返回:

public class fragment1 extends Fragment {
    @Nullable
    @Override
    // 返回的 view 對象會作為 fragment 的內容顯示在屏幕上
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment1, null);
        return v;
    }
}

第三步,在 Activity 中通過 FragmentManager 開啟事務並替換:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void click01(View v) {
        fragment fg1 = new fragment();
        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.f1, fg1);
        ft.commit();
    }

    public void click02(View v) {
        fragment1 fg2 = new fragment1();
        getFragmentManager().beginTransaction().replace(R.id.f1, fg2).commit();
    }

    public void click03(View v) {
        fragment2 fg3 = new fragment2();
        getFragmentManager().beginTransaction().replace(R.id.f1, fg3).commit();
    }
}

Activity 的布局中需要預留一個容器,這裡用 FrameLayout:

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

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="fragment01" android:onClick="click01"/>
        <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="fragment02" android:onClick="click02"/>
        <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="fragment03" android:onClick="click03"/>
    </LinearLayout>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/f1">
    </FrameLayout>
</LinearLayout>

每個 Fragment 各自的布局很簡單,例如 fragment1 就是一個紅色背景加一行文字:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ff0000">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="紅色"/>
</LinearLayout>

運行效果:點擊左側三個按鈕,右側區域顯示對應的 Fragment。

二、生命週期與切換機制

Fragment 切換時,舊的 Fragment 對象會被銷毀,新的 Fragment 對象會被創建。這意味著:

  • 每次 replace() 都是一次完整的創建—銷毀循環,Fragment 中未保存的臨時狀態會丟失,需要時應在 onSaveInstanceState() 中自行持久化。
  • 如果希望切換後保留狀態、避免重複創建,可以在切換時調用 hide()/show() 而不是 replace(),代價是內存佔用更高。
  • 若需要切換效果,可在 commit() 前用 setCustomAnimations() 或 setTransition() 添加動畫。

三、低版本兼容

support-v4 包中提供了 Fragment 相關 API,因此 Fragment 可以在低版本系統上正常使用。使用時要注意兩套 API 不能混用:

  • android.app.Fragment(API 11+)搭配 getFragmentManager();
  • android.support.v4.app.Fragment 搭配 getSupportFragmentManager()。

目前新建項目通常直接使用 AndroidX 的 androidx.fragment.app.Fragment,配合 FragmentContainerView 或 FragmentManager.commit() 完成切換,功能更完整,也更容易與 ViewModel、Navigation 組件協同。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved