編輯:關於 Android 程式設計
Fragment 可以理解為 Activity 中的一個界面模塊:它有自己的生命週期、能接收自己的輸入事件,可以在 Activity 運行時動態添加或刪除。把一個 Activity 的佈局拆成若干 Fragment,就能靈活組裝出多區域的 UI,還能在多個 Activity 之間復用。
一、兩個關鍵概念:Fragment 與宿主
Fragment 的生命週期完全依附於它的宿主 Activity:Activity 被暫停,其中所有 Fragment 一起暫停;Activity 被銷毀,Fragment 也隨之銷毀。這種依附關係決定了 Fragment 不能獨立存在。
Fragment 是 Android 3.0(API 11)引入的。有了它,你不必再手動管理視圖體系的複雜變換——Activity 的呈現方式可以在運行時修改,而這些變化會被保存在 Activity 管理的回退棧裡。
創建 Fragment 需要繼承 Fragment 類或其子類。它的代碼結構和 Activity 幾乎一樣,同樣有 onCreate()、onStart()、onPause()、onStop() 這些回調,所以把現有 Activity 的邏輯遷移到 Fragment 時,代碼基本可以按對應關係直接搬。除了基類,常用的子類還有 DialogFragment、ListFragment、PreferenceFragment。
至少應該實現的三個方法:
二、添加 Fragment 的兩種方式
(1)在 Activity 的佈局文件中声明
(2)通過 Java 代碼動態添加到已有的 ViewGroup 中
示例用兩種顏色區分兩個 Fragment:

方式一:佈局中声明
先在 layout 目錄下分別創建左右兩側的佈局文件。
第一步:left_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:background="#f">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="潘侯爺"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="碧空海"/>
</LinearLayout>
第二步:建立對應的 Fragment 類 LeftFragment.java / RightFragment.java


LeftFragment.java:
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class LeftFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// 通過 inflate 把佈局文件變成真正的 View 對象
View view = inflater.inflate(R.layout.left_layout, container, false);
return view;
}
@Override
public void onPause() {
super.onPause();
}
}
這裡 inflate 的第三個參數傳 false 很關鍵:此時 view 的 LayoutParams 由父容器在 addView 時決定,傳 true 會引發一次多餘的 attach/detach。
第三步:在主佈局 activity_main.xml 中声明兩個 fragment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context="com.example.administrator.fragmenttest.MainActivity">
<fragment
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:name="com.example.administrator.fragmenttest.LeftFragment"
tools:layout="@layout/left_layout" />
<fragment
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:name="com.example.administrator.fragmenttest.RightFragment"
tools:layout="@layout/right_layout" />
</LinearLayout>
佈局中聲明的方式簡單直接,但有一個限制:Fragment 一旦加入佈局,後續無法通過代碼替換或刪除,只能整體重建 Activity。如果需要動態切換,就得用方式二。
方式二:代碼動態添加
管理 Activity 中的 Fragment 需要 FragmentManager,通過 getFragmentManager() 獲得。它能做的事情包括:
1. 用 findFragmentById()(針對佈局中聲明的 Fragment)或 findFragmentByTag() 查找已存在的 Fragment。
2. 用 popBackStack() 模擬用戶按返回鍵,把 Fragment 從回退棧彈出。
3. 用 addOnBackStackChangedListener() 註冊回退棧變化監聽。
動態添加的核心是一系列「事務」:每一組變化由 FragmentTransaction 封裝,最終通過 commit() 提交。
第一步:主佈局 activity_main2.xml,左側仍在佈局中声明,右側留一個 FrameLayout 容器
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context="com.example.administrator.fragmenttest.MainActivity">
<fragment
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:name="com.example.administrator.fragmenttest.LeftFragment"
tools:layout="@layout/left_layout" />
<FrameLayout
android:id="@+id/right"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"></FrameLayout>
</LinearLayout>
第二步:MainActivity.java 通過事務把 RightFragment 添加進容器
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
RightFragment rightFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 獲得 FragmentManager,用於管理容器中的 Fragment
fragmentManager = getFragmentManager();
// 開啟一個事務,後續所有變更都在這個事務裡完成
fragmentTransaction = fragmentManager.beginTransaction();
rightFragment = new RightFragment();
// 把 Fragment 添加到指定容器
fragmentTransaction.add(R.id.right, rightFragment);
// 提交事務
fragmentTransaction.commit();
}
}
實踐中有幾點值得補充。add、replace、remove 三者的差別:add 是叠加,replace 是移除容器內所有 Fragment 再放入新的,remove 則是移除指定實例。如果希望切換後能通過返回鍵回退,記得在 commit 之前調用 addToBackStack(null)。另外 commit 是異步的,需要在主線程執行;在 Activity 狀態保存之後調用 commit 會拋 IllegalStateException,這種場景下應改用 commitAllowingStateLoss()。
Fragment 與 Activity 之間的通信(通過接口回調或 ViewModel 共享數據)以及 Fragment 重建時的狀態保存,是後續需要深入的部分,本文先停在兩種創建方式上。
兩行程式碼搞定 Android 視圖擴散切換動畫
用最精簡的接入方式,為 Android 視圖切換加上擴散式的過場動畫。 一、概述 這兩天動手做了一個視圖擴散切換效果的控制器,API 相容到 Android 4.0,讓畫
Android 底部彈出提示框的兩種實作方式
在 Android 中,若需要從畫面底部彈出一個提示框,並搭配半透明背景與進出動畫,常見做法有兩種:使用 Activity 搭配自訂主題,或使用 PopupWindow。
在 Eclipse 中運用 Android x86 NDK 並移植 NDK 範例應用
目標 面向 Eclipse(ADT)的 Android 外掛現在已支援基於 NDK 的應用開發,可自動產生專案與建構檔以及程式碼框架,並整合進整個 Android 開發流
Android 自定義控件:打造百分比圓環進度條
先來看看最終效果: 分析 這個進度條可以拆成三個部分: 1. 中間的圓; 2. 外邊的圓環; 3. 中間的文字。 分步繪製 這三部分都需要我們自己畫出來,因此要準備三根