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

Android Studio 實戰:從零開始寫一個 Fragment 小 Demo(上)

編輯:關於 Android 程式設計

一、先搞清楚 Fragment 到底是什麼

做 Android 開發的人大概都遇過這種尷尬:同一套功能,手機上一屏放不下,平板上卻能整整齊齊攤開。早期的做法很粗暴——先做手機版,再複製一份改成平板布局,從此兩份代碼各自演化,維護成本翻倍。

Fragment 就是為了解決這個問題而生的。它讓「一個 App 同時適配手機與平板」從口號變成可落地的方案。

你可以把 Fragment 理解成 Activity 界面的一塊拼圖,甚至整個 Activity 的界面都由幾個完全不同的 Fragment 拼出來。它擁有自己的生命週期,能獨立接收並處理用戶事件,你不必再往一個 Activity 裡塞滿密密麻麻的控件和監聽器;同時它還支持在運行期動態地添加、替換、移除。

關鍵差異在於:Fragment 承擔的是同一個 App 內部的界面切換,屬於輕量級方案(不需要在清單文件中註冊);而跨 App 的界面跳轉,仍然交給 Activity。

同一個業務界面,在平板上可以一次鋪開全部內容,在手機上則可能拆成兩個畫面。若用 Activity 實現,你得寫好幾個 Activity 去拼出平板那一屏的效果;用 Fragment,一個 Activity 就夠了。

歸納一下 Fragment 的三個核心特性:

(1)Fragment 可以作為 Activity 界面的一部分存在,一個 Activity 中能同時放多個 Fragment,同一個 Fragment 也能被多個 Activity 復用;
(2)Activity 運行過程中,Fragment 可以被動態添加、移除或替換;
(3)Fragment 能響應自己的輸入事件、擁有自己的生命週期,但這個生命週期會受宿主 Activity 的牽制。

二、Fragment 的兩種加載方式

1. 靜態加載:寫在布局文件裡

所謂靜態加載,就是在 Activity 的布局 XML 中直接寫入 fragment 標籤。先看目錄結構:

第一步,準備兩個 Fragment 的布局文件。

fragment1.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:background="#ffff2c1a">
</LinearLayout>

fragment2.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:background="#fffff353">
</LinearLayout>

第二步,寫兩個繼承自 Fragment 的類,重寫 onCreateView(),把布局文件變成 View 對象。

public class Fragment1 extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment1, container, false);
    }
}

public class Fragment2 extends Fragment {
    /**
     * Fragment 被創建時回調,返回該 Fragment 要顯示的內容
     */
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 把 layout 布局文件轉換成 View 對象
        // resource:Fragment 需要加載的布局文件
        // root:加載該布局的父容器
        // attachToRoot:false 表示不把 root 作為父容器返回
        return inflater.inflate(R.layout.fragment2, container, false);
    }
}

MainActivity 這裡反而無事可做,正常 setContentView 即可:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

第三步,回到 Activity 的布局文件,添加 fragment 標籤,name 屬性填的是 Fragment 的完整類名。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment
        android:id="@+id/fragment1"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:name="com.example.fanff.fragment01.Fragment1" />

    <fragment
        android:id="@+id/fragment2"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:name="com.example.fanff.fragment01.Fragment2" />
</LinearLayout>

兩個容易踩的坑:

① onCreateView() 是 Fragment 第一次繪制界面時被系統調用的方法,必須返回一個 View;如果這個 Fragment 不需要顯示 UI,返回 null 即可。
② 最常見的報錯是「繼承 Fragment 之後忘記重寫 onCreateView()」,如下圖的提示:

2. 動態加載:交給 FragmentTransaction

先理清幾個概念:

(1)Fragment 事務:對 Fragment 的添加、移除、替換等每一個變化,提交給 Activity 的過程。
(2)Fragment 是 UI 模塊,一個 Activity 裡自然可能不止一個模塊,所以 Android 提供了 FragmentManager 來統一管理。
(3)動態加載的套路是:先通過 FragmentManager.beginTransaction() 開啟一個事務,在其中做添加、移除等操作,最後 commit() 提交。常用方法包括 add()、remove()、replace() 和 commit()。
(4)注意:Fragment 以 ID 或 Tag 作為唯一標識,所以 remove 和 replace 傳入的 Fragment 必須與目標 Fragment 一致。

下面用手機橫豎屏加載不同 Fragment 的例子演示。前面的代碼都不用改,只改 MainActivity:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 判斷當前屏幕朝向
        int width = getWindowManager().getDefaultDisplay().getWidth();
        int height = getWindowManager().getDefaultDisplay().getHeight();

        Fragment1 f1 = new Fragment1();
        Fragment2 f2 = new Fragment2();

        FragmentManager fm = getFragmentManager();      // 獲取 Fragment 管理器
        FragmentTransaction ft = fm.beginTransaction(); // 開啟事務

        if (width > height) {          // 橫屏
            ft.replace(android.R.id.content, f1);
        } else {                       // 豎屏
            ft.replace(android.R.id.content, f2);
        }
        ft.commit();                   // 提交事務
    }
}

3. 用 Fragment 模擬選項卡切換

Tab 切換是 Fragment 最經典的用武之地:頂部一排 TextView 當標籤,點誰就把對應的 Fragment 塞進容器。

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private LinearLayout content;
    private TextView tv1, tv2, tv3, tv4;
    private FragmentManager fm;
    private FragmentTransaction ft;

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

        content = (LinearLayout) findViewById(R.id.content);
        tv1 = (TextView) findViewById(R.id.txt1);
        tv2 = (TextView) findViewById(R.id.txt2);
        tv3 = (TextView) findViewById(R.id.txt3);
        tv4 = (TextView) findViewById(R.id.txt4);

        tv1.setOnClickListener(this);
        tv2.setOnClickListener(this);
        tv3.setOnClickListener(this);
        tv4.setOnClickListener(this);

        fm = getFragmentManager();
        ft = fm.beginTransaction();
        ft.replace(R.id.content, new Fragment1());
        tv1.setBackgroundColor(Color.BLUE);
        ft.commit();
    }

    @Override
    public void onClick(View v) {
        ft = fm.beginTransaction();
        switch (v.getId()) {
            case R.id.txt1:
                ft.replace(R.id.content, new Fragment1());
                tv1.setBackgroundColor(Color.BLUE);
                clearColor(tv1);
                break;
            case R.id.txt2:
                ft.replace(R.id.content, new Fragment2());
                tv2.setBackgroundColor(Color.BLUE);
                clearColor(tv2);
                break;
            case R.id.txt3:
                ft.replace(R.id.content, new Fragment3());
                tv3.setBackgroundColor(Color.BLUE);
                clearColor(tv3);
                break;
            case R.id.txt4:
                ft.replace(R.id.content, new Fragment4());
                tv4.setBackgroundColor(Color.BLUE);
                clearColor(tv4);
                break;
        }
        ft.commit();
    }

    // 把其餘的 TextView 恢復成白色,達到「選中高亮」的效果
    private void clearColor(TextView tv) {
        switch (tv.getId()) {
            case R.id.txt1:
                tv2.setBackgroundColor(Color.WHITE);
                tv3.setBackgroundColor(Color.WHITE);
                tv4.setBackgroundColor(Color.WHITE);
                break;
            case R.id.txt2:
                tv1.setBackgroundColor(Color.WHITE);
                tv3.setBackgroundColor(Color.WHITE);
                tv4.setBackgroundColor(Color.WHITE);
                break;
            case R.id.txt3:
                tv1.setBackgroundColor(Color.WHITE);
                tv2.setBackgroundColor(Color.WHITE);
                tv4.setBackgroundColor(Color.WHITE);
                break;
            case R.id.txt4:
                tv1.setBackgroundColor(Color.WHITE);
                tv2.setBackgroundColor(Color.WHITE);
                tv3.setBackgroundColor(Color.WHITE);
                break;
        }
    }
}

三、Fragment 的向下兼容問題

如果你的 minSdk 比較低,直接用系統自帶的 Fragment 會在舊版本上崩潰,這時候要換成 support v4 支持包,一共改四處:

(1)導入的是 android.support.v4 支持包,而不是 app 包;

(2)Activity 的父類從 Activity 改為 FragmentActivity;

(3)getFragmentManager() 換成 getSupportFragmentManager();

(4)Fragment 也要改成繼承支持包裡的那個 Fragment。

小結:這一篇先把 Fragment 的靜態加載、動態加載和選項卡切換跑通。下一篇會聊聊 Fragment 的生命週期這些偏原理的內容。

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