Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 基礎:使用 Fragment 適配不同螢幕與解析度

編輯:Android 開發實例

最近工作繁忙,一個新專案急著上線,很多功能都得重做,一直在寫程式、Debug。今天因為新程式要用 Fragment 來做,雖然以前用過,但沒有仔細研究,於是趁機寫篇文章記錄 Fragment 的使用。本文主要參考 Android 官方網站的介紹。

Fragment 是 Android 3.0 之後新增的元件,有點類似 Activity,同樣用來承載各種 View 元素。Google 增加它的目的,是為了讓平板電腦能複用部分顯示的 View——只要寫好一個 View,就能同時在手機、平板等不同尺寸的設備上使用,而這個轉換過程系統會幫你搞定。

1. 為何使用 Fragment

Android 官網用一個例子說明 Fragment 的作用:一個新聞應用可以在螢幕左側用一個 Fragment 展示文章列表,右側用另一個 Fragment 展示文章內容——兩個 Fragment 並排顯示在同一個 Activity 中,各自擁有生命週期回呼並處理自己的使用者輸入事件。如此一來,使用者便能在同一個 Activity 中選擇並閱讀文章。

當運行在特別大的螢幕(如平板電腦)上時,應用可以在 Activity A 中嵌入兩個 Fragment;但在正常尺寸螢幕(如手機)上,沒有足夠空間同時容納兩個 Fragment,此時 Activity A 只包含文章列表 Fragment,使用者選擇文章後再啟動包含閱讀 Fragment 的 Activity B。這樣,應用便能同時支持這兩種設計模式。

由於 Fragment 定義了自己的佈局,並透過生命週期回呼定義了自己的行為,你可以把它包含到多個 Activity 中。這點特別重要,因為它讓你能把使用者體驗適配到不同的螢幕尺寸。

2. 建立 Fragment

要建立 Fragment,必須建立一個 Fragment 的子類(或繼承自現有的子類)。Fragment 類別的程式碼看起來很像 Activity,包含類似的回呼方法,如 onCreate()、onStart()、onPause()、onStop()。事實上,若要把現成的應用轉換為使用 Fragment,可能只需把程式碼從 Activity 的回呼搬到 Fragment 的回呼即可。

Fragment 的常見子類有:

•DialogFragment:顯示一個浮動的對話框。相較於 Activity 的對話框工具方法,它的好處是可以把對話框 Fragment 合併到 Activity 管理的 back stack,讓使用者返回之前關閉的 Fragment。
•ListFragment:顯示一個由 adapter(如 SimpleCursorAdapter)管理的項目列表,類似 ListActivity,並提供 onListItemClick() 回呼來處理點擊事件。
•PreferenceFragment:顯示 Preference 物件的階層結構列表,類似 PreferenceActivity,適合為應用建立「設定」畫面。

3. Fragment 生命週期

以下為 Fragment 的生命週期圖,摘自 Android 官網:

繼承 Fragment 相關類別後,我們需要覆寫幾個回呼函式來實作功能。以下三個是我們一般都會覆寫的方法:

public class MainFragment extends Fragment
{
    //創建Fragment
    public void onCreate()
    {}
    //返回View給Activity使用
    public View onCreateView()
    {}
    public void onPause()
    {}
}

•onCreate():建立 Fragment 時系統呼叫,應在此初始化想保留的元件,以便 Fragment 暫停或停止後可恢復。
•onCreateView():Fragment 第一次繪製 UI 時呼叫,必須返回一個 View(Fragment 佈局的根 View);若不提供 UI,可返回 null。
•onPause():使用者即將離開 Fragment 時呼叫,通常應在此提交任何需要持久化的變化。

4. 為 Fragment 提供佈局

要為 Fragment 提供佈局,必須實作 onCreateView() 回呼,並返回 Fragment 佈局的根 View。若你的 Fragment 是 ListFragment 子類,其預設實作會返回一個 ListView,通常不必自己實作。

從 XML 載入 View 的範例如下:

public static class ExampleFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                            Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.example_fragment, container, false);
    }
}

傳入 onCreateView() 的 container 參數是 Fragment 佈局將被插入的父 ViewGroup;savedInstanceState 則在 Fragment 被恢復時提供之前實例的資料。inflate() 方法有三個參數:

•resource ID:想加載的佈局資源 ID。
•container:加載佈局的父 ViewGroup,傳入它是為了讓系統正確套用根 View 的 layout 參數。
•boolean:指示加載期間是否把展開的佈局附著到 ViewGroup。此例傳入 false,因為系統已把展開的佈局插入 container,傳入 true 會產生多餘的 view group。

5. 把 Fragment 添加到 Activity

Fragment 通常作為宿主 Activity UI 的一部分被嵌入,有兩種添加方式:

方法一:在 Activity 的佈局檔中聲明 Fragment。此時可像為 View 一樣為 Fragment 指定 layout 屬性。以下是一個含兩個 Fragment 的 Activity 佈局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <fragment android:name="com.example.news.ArticleListFragment"
            android:id="@+id/list"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
    <fragment android:name="com.example.news.ArticleReaderFragment"
            android:id="@+id/viewer"
            android:layout_weight="2"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
</LinearLayout>

<fragment> 中的 android:name 屬性指定了在佈局中實例化的 Fragment 類別。當系統建立 Activity 佈局時,會實例化每個指定的 Fragment,並呼叫其 onCreateView() 取得佈局,再插入到 <fragment> 元素所在的位置。每個 Fragment 都需要一個唯一標識,以便 Activity 重啟時恢復 Fragment,也方便你捕獲 Fragment 來處理事務。

提供 Fragment 標識有三種方法:為 android:id 提供唯一 ID;為 android:tag 提供唯一字串;若都未提供,系統會使用容器 View 的 ID。

方法二:撰寫程式碼將 Fragment 添加到已存在的 ViewGroup。Activity 運行的任何時候都能添加 Fragment,只需指定放置它的 ViewGroup。要操作 Fragment 事務(新增、移除、替換),必須使用 FragmentTransaction 的 API:

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

接著用 add() 方法添加 Fragment,指定要添加的 Fragment 與要插入的 View:

fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();

add() 的第一個參數是 Fragment 要放入的 ViewGroup(由 resource ID 指定),第二個參數是要添加的 Fragment。完成變化後,必須呼叫 commit() 才能使其生效。

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