編輯:Android 開發實例
我們都知道,Android 的畫面展示一直是靠 Activity 撐起來的。Activity 實在太常用了,相信大家都已經很熟悉,這裡就不再多贅述。
但 Activity 也有它的侷限。同一個介面在手機上或許賞心悅目,換到平板上就未必了——平板螢幕大得多,把手機介面直接搬過去,往往會出現過度拉長、控制項間距過大等尷尬情況。這時候更好的做法是,在一個 Activity 裡嵌入若干「小 Activity」,每個「小 Activity」又各自擁有獨立布局。於是,今天的主角 Fragment 正式登場。
Fragment 初探
為了讓介面在平板上呈現得更好,Android 從 3.0 版引入了 Fragment(碎片)功能。它與 Activity 極為相似,同樣能承載布局,但 Fragment 通常是嵌套在 Activity 裡使用的。想像這樣一個場景:有兩個 Fragment,Fragment 1 內含一個 ListView,每一列顯示一本書的標題;Fragment 2 則包含 TextView 與 ImageView,用來顯示書籍的詳細內容與封面。
如果程式運行在直屏的手機或平板上,Fragment 1 可能嵌在一個 Activity 裡,Fragment 2 嵌在另一個 Activity 裡,如下圖:
而如果程式運行在橫屏的平板上,這兩個 Fragment 就可以同時嵌進同一個 Activity,如下圖:
由此可見,善用 Fragment 能讓我們更充分地利用平板的螢幕空間。下面我們一起來看看 Fragment 到底怎麼用。
先提醒一點:Fragment 是在 3.0 版才引入的,如果你用的是 3.0 以前的系統,得先匯入 android-support-v4 的 jar 套件才能使用。
新建一個名為 Fragments 的專案,在 layout 資料夾下建立 fragment1.xml:
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="#00ff00" >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="This is fragment 1"
- android:textColor="#000000"
- android:textSize="25sp" />
- </LinearLayout>
這個布局非常單純,一個 LinearLayout 裡放一個 TextView。如法炮製再建 fragment2.xml:
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="#ffff00" >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="This is fragment 2"
- android:textColor="#000000"
- android:textSize="25sp" />
- </LinearLayout>
然後新建 Fragment1 類別,繼承自 Fragment:
- public class Fragment1 extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- return inflater.inflate(R.layout.fragment1, container, false);
- }
- }
這個類別也很簡單,主要就是載入剛寫好的 fragment1.xml 並返回。用同樣方式寫好 Fragment2:
- public class Fragment2 extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- return inflater.inflate(R.layout.fragment2, container, false);
- }
- }
接著打開或建立 activity_main.xml 作為主 Activity 布局,在其中引用這兩個 Fragment,用 android:name 前綴指向具體的 Fragment:
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:baselineAligned="false" >
- <fragment
- android:id="@+id/fragment1"
- android:name="com.example.fragmentdemo.Fragment1"
- android:layout_width="0dip"
- android:layout_height="match_parent"
- android:layout_weight="1" />
- <fragment
- android:id="@+id/fragment2"
- android:name="com.example.fragmentdemo.Fragment2"
- android:layout_width="0dip"
- android:layout_height="match_parent"
- android:layout_weight="1" />
- </LinearLayout>
最後打開或建立 MainActivity,程式碼都是自動生成的:
- public class MainActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- }
- }
跑一次程式就會看到,一個 Activity 和諧地容納了兩個 Fragment,它們平分整個螢幕:
動態添加 Fragment
你已經學會如何在 XML 裡使用 Fragment,但這僅僅是它最基礎的用法。Fragment 真正的強大之處,在於能夠在執行期動態地加入 Activity,這也是你必須掌握的技能。學會在程式運行時動態添加 Fragment,介面就能被客製得多樣化。下面我們馬上來看怎麼做。
仍在前一節程式碼的基礎上修改。打開 activity_main.xml,把其中對 Fragment 的引用全部刪掉,只保留最外層的 LinearLayout,並幫它加上一個 id,因為接下來要用程式碼動態添加,XML 裡不再寫死:
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:id="@+id/main_layout"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:baselineAligned="false" >
- </LinearLayout>
接著打開 MainActivity,改成如下:
- public class MainActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- Display display = getWindowManager().getDefaultDisplay();
- if (display.getWidth() > display.getHeight()) {
- Fragment1 fragment1 = new Fragment1();
- getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit();
- } else {
- Fragment2 fragment2 = new Fragment2();
- getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment2).commit();
- }
- }
- }
我們先取得螢幕寬高並加以判斷:寬度大於高度就添加 fragment1,高度大於寬度就添加 fragment2。動態添加 Fragment 主要分四步:
1. 取得 FragmentManager,在 Activity 中可直接用 getFragmentManager 拿到。
2. 開啟一個事務,呼叫 beginTransaction 方法。
3. 把 Fragment 加入容器,一般用 replace 方法,傳入容器 id 與 Fragment 實例。
4. 提交事務,呼叫 commit 方法。
現在跑起來看看:
如果你用的是模擬器,按 ctrl + F11 可切換到直屏模式:
Fragment 的生命週期
和 Activity 一樣,Fragment 也有自己的生命週期。理解它非常重要,我們用程式碼實際觀察一下:
- public class Fragment1 extends Fragment {
- public static final String TAG = "Fragment1";
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- Log.d(TAG, "onCreateView");
- return inflater.inflate(R.layout.fragment1, container, false);
- }
- @Override
- public void onAttach(Activity activity) {
- super.onAttach(activity);
- Log.d(TAG, "onAttach");
- }
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- Log.d(TAG, "onCreate");
- }
- @Override
- public void onActivityCreated(Bundle savedInstanceState) {
- super.onActivityCreated(savedInstanceState);
- Log.d(TAG, "onActivityCreated");
- }
- @Override
- public void onStart() {
- super.onStart();
- Log.d(TAG, "onStart");
- }
- @Override
- public void onResume() {
- super.onResume();
- Log.d(TAG, "onResume");
- }
- @Override
- public void onPause() {
- super.onPause();
- Log.d(TAG, "onPause");
- }
- @Override
- public void onStop() {
- super.onStop();
- Log.d(TAG, "onStop");
- }
- @Override
- public void onDestroyView() {
- super.onDestroyView();
- Log.d(TAG, "onDestroyView");
- }
- @Override
- public void onDestroy() {
- super.onDestroy();
- Log.d(TAG, "onDestroy");
- }
- @Override
- public void onDetach() {
- super.onDetach();
- Log.d(TAG, "onDetach");
- }
- }
上面的程式碼在每個生命週期方法裡都印了日誌。跑起來看看輸出:
這時按一下 home 鍵,日誌如下:
再重新進入程式,日誌如下:
然後按 back 鍵退出,日誌如下:
看到這裡,相信大多數朋友都已經很清楚了,因為它與 Activity 的生命週期實在太像了。只是有幾個 Activity 沒有的新方法,這裡重點介紹一下:
Fragment 之間進行通信
一般情況下,一個 Activity 會包含多個 Fragment,這時候多個 Fragment 之間如何通信就成了關鍵。我們用一個例子來看看,如何在一個 Fragment 中去存取另一個 Fragment 的視圖。
還在第一節程式碼的基礎上修改。先打開 fragment2.xml,加入一顆按鈕:
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- android:background="#ffff00" >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="This is fragment 2"
- android:textColor="#000000"
- android:textSize="25sp" />
- <Button
- android:id="@+id/button"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Get fragment1 text"
- />
- </LinearLayout>
然後打開 fragment1.xml,為 TextView 加上一個 id:
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="#00ff00" >
- <TextView
- android:id="@+id/fragment1_text"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="This is fragment 1"
- android:textColor="#000000"
- android:textSize="25sp" />
- </LinearLayout>
接著打開 Fragment2.java,加入 onActivityCreated 方法並處理按鈕點擊:
- public class Fragment2 extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- return inflater.inflate(R.layout.fragment2, container, false);
- }
- @Override
- public void onActivityCreated(Bundle savedInstanceState) {
- super.onActivityCreated(savedInstanceState);
- Button button = (Button) getActivity().findViewById(R.id.button);
- button.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- TextView textView = (TextView) getActivity().findViewById(R.id.fragment1_text);
- Toast.makeText(getActivity(), textView.getText(), Toast.LENGTH_LONG).show();
- }
- });
- }
- }
跑起來,點一下 fragment2 上的按鈕:
可以看到,fragment2 成功取得了 fragment1 中的視圖並彈出 Toast。這是怎麼做到的呢?關鍵都在 getActivity 這個方法。它能讓 Fragment 取得關聯的 Activity,再呼叫 Activity 的 findViewById,就能拿到同一個 Activity 下其他 Fragment 的視圖了。
好了,以上就是關於 Fragment 你必須知道的一切。若想親身體驗 Fragment 的實戰,請繼續閱讀後續文章。
Android 登入畫面實作教學:帳密驗證與錯誤嘗試鎖定
登入畫面通常會要求使用者輸入一組憑證,才能進入某個特定應用,例如 Facebook、微博等服務的授權登入。 本章要介紹如何建立一個登入介面,並處理其中的安全設計與錯誤嘗試
Android Virtual Device 建立與啟動教學
AVD 是什麼 Android Virtual Device 是 Android 模擬器的虛擬裝置設定。每個 AVD 可指定系統版本、螢幕配置與硬體參數,讓開發者模擬不同
Android Spinner 進度條:按鈕觸發與顯示控制
Spinner 的顯示時機當使用者等待網路請求、檔案讀取或資料處理時,不確定型進度條可以作為視覺回饋。Android 中通常使用 ProgressBar 搭配 large
Android 二級下拉菜單與實時搜索聯動的實現方法
需求很常見:頁面上方一個搜索框,下方一個兩級菜單;有輸入時展示搜索結果列表,清空輸入後恢復菜單。本文用 ExpandableListView + ListView 的顯示