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

Android Fragment 完全解析:關於碎片你所需知道的一切

編輯:關於 Android 開發

Android Fragment 完全解析:關於碎片你所需知道的一切

我們都知道,Android 上的介面展示都是透過 Activity 實現的,Activity 實在是太常用了,相信大家都已經非常熟悉,這裡就不再贅述。

但 Activity 也有它的侷限:同一個介面在手機上顯示可能很好看,放到平板上卻未必如此。因為平板螢幕非常大,手機介面放上去可能會出現過分被拉長、控制項間距過大等情況。這時候,更好的體驗是在 Activity 中嵌入「小 Activity」,而每個「小 Activity」又能擁有自己的布局。因此,今天的主角 Fragment 登場了。

Fragment 初探

為了讓介面能在平板上更好地展示,Android 在 3.0 版本引入了 Fragment(碎片)功能。它非常類似於 Activity,可以像 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 包才能使用 Fragment 功能。

新建一個名為 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>

現在我們來運行一次程式,就會看到,一個 Activity 很融洽地包含了兩個 Fragment,這兩個 Fragment 平分了整個螢幕,效果圖如下:

動態添加 Fragment

你已經學會了如何在 XML 中使用 Fragment,但這僅僅是 Fragment 最簡單的功能而已。Fragment 真正強大之處,在於可以動態地添加到 Activity 當中,因此這也是你必須掌握的東西。當你學會了在程式運行時向 Activity 添加 Fragment,程式的介面就能定制得更加多樣化。下面我們立刻來看看如何動態添加 Fragment。

還是在上一節程式碼的基礎上修改,打開 activity_main.xml,將其中對 Fragment 的引用都刪除,只保留最外層的 LinearLayout,並給它添加一個 id,因為我們要動態添加 Fragment,就不用在 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 也有自己的生命週期。理解 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 中沒有的新方法,這裡需要重點介紹一下:

  • onAttach 方法:Fragment 和 Activity 建立關聯的時候調用。
  • onCreateView 方法:為 Fragment 加載布局時調用。
  • onActivityCreated 方法:當 Activity 中的 onCreate 方法執行完後調用。
  • onDestroyView 方法:Fragment 中的布局被移除時調用。
  • onDetach 方法:Fragment 和 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 這個方法實現的。getActivity 方法可以讓 Fragment 獲取到關聯的 Activity,然後再調用 Activity 的 findViewById 方法,就可以獲取到和這個 Activity 關聯的其他 Fragment 的視圖了。

好了,以上就是關於 Fragment 你所須知道的一切。如果想要切身體驗一下 Fragment 的實戰,請繼續閱讀 Android 手機平板兩不誤,使用 Fragment 實現兼容手機和平板的程式 以及 Android Fragment 應用實戰,使用碎片向 ActivityGroup 說再見。

轉載於:https://blog.csdn.net/guolin_blog/article/details/8881711

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