編輯:Android 開發實例
前言
本文將帶你完整認識 Android 中的 Fragment,關鍵環節都會附上可運行的示範程式碼,最後並提供源碼下載。
本文涵蓋:
什麼是 Fragment
Fragment,中文譯為「碎片」,是 Android 3.0 之後新增的特性,主要是為了在大螢幕裝置(如平板)上支援更靈活的 UI 設計。隨著裝置螢幕日益增大,善用 Fragment 能更從容地管理視圖層次的變化。與 Activity 類似,我們可以建立 Fragment 來承載 View、進行布局,但 Fragment 必須嵌入 Activity 之中,無法單獨存在;而且一個 Activity 可以嵌入多個 Fragment,同一個 Fragment 也能被多個 Activity 重複使用。
下圖引自官方文件,清楚說明了 Activity 與 Fragment 的關係與優勢。在平板上,由於螢幕大、可顯示的內容多,若還像手機那樣靠 Activity 跳轉來切換 UI,未免太浪費螢幕空間。如左圖所示,透過 Fragment 布局,可讓一個 Activity 左右各嵌一個 Fragment,於是操作左側 Fragment 就能即時影響右側 Fragment 的顯示,典型場景如新聞閱讀、系統設定等。若一個應用採用 Activity + Fragment 的組合布局,便能輕鬆在手機與平板間互相移植,大部分程式碼都能重用,而且 Fragment 無需在 AndroidManifest.xml 清單檔中註冊。
如何建立一個 Fragment
認識了 Fragment,接著談談怎麼用。使用 Fragment 必須繼承 Fragment 類或其子類,並重寫 onCreateView() 方法——這個方法用來指定 Fragment 初次載入時顯示的 View。其簽名如下:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
onCreateView() 需回傳一個 View 供 Fragment 顯示,這裡以 inflater.inflate() 動態膨脹出一個 View 作為回傳值,inflate() 的簽名如下:
public View inflate(int resource, ViewGroup root, boolean attachToRoot)
inflate() 的 resource 就是一個普通的布局資源,別無特殊。而在布局檔中使用 Fragment,則需用 <fragment/> 標籤,多數屬性與一般 UI 控件相同,但有兩個屬性要特別留意:
以下用一個範例,演示 Fragment 在 Activity 中的應用,在單一 Activity 裡加入兩個 Fragment。
activity_fragment.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="horizontal" >
- <fragment
- android:id="@+id/fragment1"
- android:name="com.example.fragmentSimple.Fragment1"
- android:layout_width="0px"
- android:layout_height="match_parent"
- android:layout_weight="2" />
- <fragment
- android:id="@+id/fragment2"
- android:name="com.example.fragmentSimple.Fragment2"
- android:layout_width="0px"
- android:layout_height="match_parent"
- android:layout_weight="1" />
- </LinearLayout>
Fragment1:
- package com.example.fragmentSimple;
- import com.example.fragmentdemo.R;
- import android.app.Fragment;
- import android.os.Bundle;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
- public class Fragment1 extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- // 填充一個布局View到ViewGrope中
- return inflater.inflate(R.layout.fragment1, container, false);
- }
- }
Fragment2:
- package com.example.fragmentSimple;
- import com.example.fragmentdemo.R;
- import android.os.Bundle;
- import android.app.Fragment;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
- public class Fragment2 extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- return inflater.inflate(R.layout.fragment2, container, false);
- }
- }
啟動後的顯示效果:
Fragment 的生命週期
Fragment 擁有自己獨立的生命週期,但它依附於 Activity,因此其生命週期直接受 Activity 牽動。下圖很直觀地描繪了 Fragment 的生命週期:
從圖中不難看出,Fragment 的生命週期大體與 Activity 相仿,但有兩個方法值得留意:onAttach()(附加)與 onDetach()(剝離)。從這兩者的位置可知,Fragment 在建立時會先附加到 Activity,之後才從 onCreateView() 載入 View——這一點相當重要。而在生命週期終點,順序則相反:先銷毀 onDestroy(),再回呼 onDetach() 從 Activity 剝離該 Fragment。
如何管理一個 Fragment
在程式碼中管理 Fragment 相當簡單,關鍵在於一個 FragmentTransaction 物件。它透過 getFragmentManager().beginTransaction() 取得,會開啟一個事務,用來操作某個 ViewGroup 中的 Fragment。
FragmentTransaction 的常用方法:
其中 add、replace、remove 都是常見操作,無須多作解釋。但 addToBackStack() 就得額外說明。正常情況下,應用中的 Activity 由一個任務堆疊管理,我們在不同 Activity 間跳轉時,按返回鍵总能回到上一個 Activity。而 Fragment 是嵌套在 Activity 裡的,預設無法進入 Activity 的任務堆疊,因此按返回時只會回到上一個 Activity,不會理會 Fragment 的操作(add、replace、remove)。而 addToBackStack() 能把當前事務加入另一個由 Fragment 所屬 Activity 管理的堆疊,這個堆疊的每一筆都是 Fragment 的一次事務;有了它,便能透過返回鍵反向回滾 Fragment 的事務。這一點相當關鍵,因為 Fragment 無需在清單檔中配置,如今有些應用正是靠 Fragment 來完成布局跳轉。
以下用一個範例,演示動態操作 Fragment:實作一個分欄效果,點擊左側項目會動態改變右側內容。
布局檔 activity_fragmenttab.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="horizontal" >
- <LinearLayout
- android:layout_width="wrap_content"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- <TextView
- android:id="@+id/tabfgt1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="fragment1" />
- <TextView
- android:id="@+id/tabfgt2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="fragment2" />
- <TextView
- android:id="@+id/tabfgt3"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="fragment3" />
- </LinearLayout>
- <LinearLayout
- android:id="@+id/content"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- </LinearLayout>
- </LinearLayout>
FragmentTabActivity.java:
- package com.example.fragmentTab;
- import com.example.fragmentSimple.Fragment1;
- import com.example.fragmentSimple.Fragment2;
- import com.example.fragmentTurn.Fragment3;
- import com.example.fragmentdemo.R;
- import android.app.Activity;
- import android.app.FragmentManager;
- import android.app.FragmentTransaction;
- import android.graphics.Color;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.TextView;
- public class FragmentTabActivity extends Activity {
- private TextView tabfgt1, tabfgt2, tabfgt3;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_fragmenttab);
- tabfgt1 = (TextView) findViewById(R.id.tabfgt1);
- tabfgt2 = (TextView) findViewById(R.id.tabfgt2);
- tabfgt3 = (TextView) findViewById(R.id.tabfgt3);
- tabfgt1.setOnClickListener(click);
- tabfgt2.setOnClickListener(click);
- tabfgt3.setOnClickListener(click);
- }
- private View.OnClickListener click = new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- tabfgt1.setBackgroundColor(Color.GRAY);
- tabfgt2.setBackgroundColor(Color.GRAY);
- tabfgt3.setBackgroundColor(Color.GRAY);
- // 獲取FragmentManager對象
- FragmentManager fm = getFragmentManager();
- // 開啟事務
- FragmentTransaction ft = fm.beginTransaction();
- switch (v.getId()) {
- case R.id.tabfgt1:
- tabfgt1.setBackgroundColor(Color.GREEN);
- // 替換R.id.content中的Fragment
- ft.replace(R.id.content, new Fragment1());
- break;
- case R.id.tabfgt2:
- tabfgt2.setBackgroundColor(Color.YELLOW);
- ft.replace(R.id.content, new Fragment2());
- break;
- case R.id.tabfgt3:
- tabfgt3.setBackgroundColor(Color.RED);
- ft.replace(R.id.content, new Fragment3());
- break;
- default:
- break;
- }
- // 提交事務
- ft.commit();
- }
- };
- }
效果展示:
Fragment 之間如何互動
既然 Fragment 嵌套在 Activity 中,而 Fragment 載入的布局檔裡又能再放額外布局,於是就冒出一個新問題:該如何操作分屬不同 Fragment 的控件呢?回想一下,在 Activity 中操作控件是靠 findViewById(int) 透過 ID 找到它;而 Fragment 最終在 onCreateActivity() 階段會把膨脹的 View 掛載到 Activity 上,因此可以直接在 Activity 中用 findViewById() 找到控件進而操作,這與直接操作 Activity 的方式一致。但若要在某個 Fragment 中操作另一個 Fragment 的控件,就得借助 Fragment.getActivity() 取得當前 Fragment 所依附的 Activity 物件,拿到它之後,要取其中的控件自然不成問題。
以下用一個範例演示 Fragment 間的互動:Activity 中有三個 Fragment,從其中一個 Fragment 的 Button 點擊時,去修改其他 Fragment 的值。
布局 activity_fragmentturn.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="horizontal" >
- <fragment
- android:id="@+id/fragment1"
- android:name="com.example.fragmentSimple.Fragment1"
- android:layout_width="0px"
- android:layout_height="match_parent"
- android:layout_weight="1" />
- <!-- 加載了兩個Fragment1 -->
- <fragment
- android:id="@+id/fragment2"
- android:name="com.example.fragmentSimple.Fragment1"
- android:layout_width="0px"
- android:layout_height="match_parent"
- android:layout_weight="1" />
- <fragment
- android:id="@+id/fragment3"
- android:name="com.example.fragmentTurn.Fragment3"
- android:layout_width="0px"
- android:layout_height="match_parent"
- android:layout_weight="1" />
- </LinearLayout>
帶 Button 的 Fragment:
- package com.example.fragmentTurn;
- import com.example.fragmentdemo.R;
- import android.app.Fragment;
- import android.os.Bundle;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.Button;
- import android.widget.TextView;
- import android.widget.Toast;
- public class Fragment3 extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- return inflater.inflate(R.layout.fragment3, container, false);
- }
- @Override
- public void onStart() {
- super.onStart();
- // 方法2: 在Fragment中獲取操作其他Fragment的控件
- // Button btnGetText=(Button)getActivity().findViewById(R.id.btnGetText);
- // btnGetText.setOnClickListener(new View.OnClickListener() {
- //
- // @Override
- // public void onClick(View v) {
- // TextView tv=(TextView)getActivity().findViewById(R.id.tvFragment1);
- // Toast.makeText(getActivity(), tv.getText().toString() ,Toast.LENGTH_SHORT).show();
- // }
- // });
- }
- }
FragmentTurnActivity.java:
- package com.example.fragmentTurn;
- import com.example.fragmentdemo.R;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.Button;
- import android.widget.TextView;
- import android.widget.Toast;
- public class FragmentTurnActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_fragmentturn);
- // 方法1:在Activity中操作旗下Fragment中的控件
- Button btn=(Button)findViewById(R.id.btnGetText);
- btn.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- TextView tv=(TextView)findViewById(R.id.tvFragment1);
- tv.setText("動態修改");
- Toast.makeText(FragmentTurnActivity.this,tv.getText().toString() ,Toast.LENGTH_SHORT ).show();
- }
- });
- }
- }
效果展示:
上面的例子還藏著一個陷阱:無論在 Activity 中用 findViewById(),還是在 Fragment 中用 getActivity().findViewById(),雖然都能取到控件,但有個例外——當 Activity 中同時放了兩個一模一樣的 Fragment 時,僅靠上述方法只能透過 ID 取到第一個 Fragment 裡的控件。原因在於,布局檔中定義的控件即便 ID 重複,Android SDK 維護的 R.java 也只會宣告一次,也就是說,想在 Activity 中區分同一 Fragment 類別的兩個實例裡的控件,是辦不到的。
那只好換個思路。我的解法是:在 Fragment 中宣告一個 View 變數,於 onCreateView 中把膨脹的 View 不直接回傳,而是先引用到這個變數上;之後在需要的任何地方,用 getFragmentManager().findFragmentById(int) 透過 Fragment 的 ID 找到該物件,再取出其中的 View,用 View.findViewById(int) 定位到對應 ID 的控件進而操作(這裡就不另附範例了)。這方法雖能解決問題,但一般並不推薦,因為大多數場景根本没必要在一個 Activity 裡放兩個相同的 Fragment。
Fragment 的向下相容
前面提過,Fragment 是 Android 3.0 之後才有的特性。而對於低版本的裝置,Google 也沒放著不管。細心的朋友應該會發現,引入 Fragment 的套件時有兩個選項:android.app.Fragment 與 android.support.v4.app.Fragment,其中後者正是為了相容低版本而準備的,直接引用它即可。
一般來說,若考慮向下相容,建議直接引用 android.support.v4.app.Fragment 進行開發,就不必再為相容性煩惱。
源碼下載
Android手機衛士(十九):建立首次密碼設定畫面
本篇要完成的是手機衛士中「第一次設定密碼」的流程。當使用者首次進入手機防盜功能時,必須先建立一組密碼,後續才能進行驗證與保護。畫面配置這個頁面可以採用垂直 LinearL
Android 應用本地化:讓 App 說多國語言
同一支應用程式,可能會被安裝在台灣、義大利、德國或日本的裝置上。要讓不同地區的使用者都覺得順手,文字、數字、日期與檔案格式都得跟著系統語言環境調整,這就是「本地化」(Lo
Android 自訂 ViewGroup 打造多風格 SlidingMenu
側滑選單是許多 App 常見的互動模式。本文以自訂 ViewGroup 的方式,從最基礎的側滑菜單開始,逐步加入 Scroller 自動吸附、事件攔截、滑動衝突處理,最後
為 Android 系統加入「按電源鍵掛斷電話」功能
現在多數 Android 手機都內建了「按電源鍵結束通話」的選項,通常放在通話設定裡。但在原生原始碼中,這一項並不存在,得自己加。以下記錄我在學習過程中改動原生碼的完整思