編輯:關於 Android 程式設計
Fragment 的誕生,一方面旨在緩解 Activity 任務過重的問題,另一方面則是為了從容應對不同螢幕尺寸下 UI 組件的佈局難題,而且它還帶來了一些嶄新的特性(例如 Retainable),用來處理那些過去在 Activity 中頗為棘手的老問題。Fragment 擁有與 Activity 一致的生命週期,同樣被定義為 Controller 層的類。凡是有過中大型項目開發經驗的開發者,想必都曾遭遇過 Activity 過度臃腫的窘境,而 Fragment 的出現正是為了化解這一困境——可以說,它把螢幕拆解為多個「Fragment(碎片)」(這句話至關重要),但它又與 View 有著本質的不同,它所干的其實就是 Activity 的活兒,負責控制 View 以及它們之間的邏輯。把螢幕碎片化成多個 Fragment 之後,Activity 便只需集中精力去管理當前螢幕內應該顯示哪些 Fragments,以及如何對它們進行佈局即可。這是一種組件化的思維:用 Fragment 去組合一系列有關聯的 UI 組件並管理它們之間的邏輯,而 Activity 則負責在不同螢幕下(例如橫屏與豎屏)佈局不同的 Fragments 組合。這種碎片不僅能管理可視的 Views,也能執行不可視的 Tasks;它提供了 retainInstance 屬性,使得 Activity 因螢幕狀態改變(例如切換橫豎屏)而銷毀重建時,仍能保留實例。這意味著我們能在 RetainedFragment 裡執行一些在螢幕狀態改變時不被中斷的操作。
下面我們就來具體看一個 Android Fragment 功能的例子。
要實現的功能很簡單,也最為基礎:上下分別是兩個 Fragment,上方的 Fragment 中是一個 listview,當點擊 item 時,下方的 Fragment 便顯示對應的文字詳細信息:


具體的實現步驟如下:
①創建工程 FragmentExam,目錄視圖如下(順帶把之前的 FragmentPreference 的 demo 也加到了一起):

②main.xml 檔案佈局,垂直方向上擺放兩個 Fragment,用 <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" android:orientation="vertical" android:background="#7ecef4"> <fragment android:name="com.example.fragementexam.FragementList" android:id="@+id/frag_list" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="2"/> <fragment android:name="com.example.fragementexam.FragementDetails" android:id="@+id/frag_detail" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1"/> </LinearLayout>
③FragementList.java 的程式碼,它繼承了 ListFragment,注意在 onCreateView 方法中使用 inflater 的 inflate 方法把佈局頁面引入:
package com.example.fragementexam; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.ListFragment; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.SimpleAdapter; public class FragementList extends ListFragment { private String[] values = new String[] { "侏儒", "人類", "暗夜精靈", "矮人", "德萊尼", "狼人" }; private int[] images = new int[] { R.drawable.gnome, R.drawable.human, R.drawable.nightelf, R.drawable.dwarf, R.drawable.draenei, R.drawable.werewolf }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.frag_list, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>(); for (int i = 0; i < values.length; i++) { Map<String, Object> listItem = new HashMap<String, Object>(); listItem.put("values", values[i]); listItem.put("images", images[i]); listItems.add(listItem); } SimpleAdapter adapter = new SimpleAdapter(getActivity(), listItems, R.layout.list_item, new String[] { "values", "images" }, new int[] { R.id.txt_title, R.id.img }); setListAdapter(adapter); } @Override public void onListItemClick(ListView l, View v, int position, long id) { // String item = (String) getListAdapter().getItem(position); FragementDetails frag = (FragementDetails) getFragmentManager() .findFragmentById(R.id.frag_detail); if (frag != null && frag.isInLayout()) { switch (position) { case 0: frag.setText(getString(R.string.Gnome)); break; case 1: frag.setText(getString(R.string.Human)); break; case 2: frag.setText(getString(R.string.NightElf)); break; case 3: frag.setText(getString(R.string.Dwarf)); break; case 4: frag.setText(getString(R.string.Draenei)); break; case 5: frag.setText(getString(R.string.Werewolf)); break; } } Log.i("PDA", "position = " + position); } } ④FragementDetails.java 的程式碼,這個相對簡單,裡面有一個設置 TextView 內容的方法,其佈局頁面也僅僅是一個 TextView
package com.example.fragementexam; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class FragementDetails extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub return inflater.inflate(R.layout.frag_detail, container,false); } public void setText(String item){ TextView txt = (TextView) getView().findViewById(R.id.txt_detail); txt.setText(item); }
其餘的部分無非是一些陣列與 String 的定義了。這個 demo 雖然簡單,卻把 Android Fragment 方面常用的知識做了一次綜合演練。若能把這份程式碼徹底寫明白,日後再遇到類似的項目,應該就能應付得游刃有餘了。好了,收工!
Cordova 自定義插件開發完整流程解析
環境準備開發 Cordova 自定義插件前,需要先準備 Node.js、Cordova 命令列工具與 Android SDK。安裝完成後,可透過 npm 與 cordov
工廠模式到底有什麼用?用麥當勞點餐與線程池一次講透
先把那個心結說開 很多人第一次接觸工廠模式時都會有同樣的疑問:既然對象的職責就是「被創建」,那直接 new 一個不就完了,為什麼還要再包一層工廠類,讓工廠去幫你 new?
Android 藍牙開發入門:開啟、可見性、搜索與連線
BluetoothAdapter 基本概念 Android 藍牙開發通常以 BluetoothAdapter 為核心。它負責管理本機藍牙狀態、搜尋裝置、取得遠端裝置與建立
Android 使用 AIDL 實現跨進程調用 Service 的完整教學
一、問題描述 Android 應用程式的四大組件——Activity、BroadcastReceiver、ContentProvider、Service,都可以進行跨進程