Android百議程序: Fragment動態管理和生命期

來源:互聯網
上載者:User

標籤:

之前寫過Fragment使用的程式,Fragment可以靜態,也可以動態載入記憶體中的,這一章進一步看看如何動態地更換Fragment和看看Fragment生命期都有什麼函數。


本章利用響應菜單點擊事件,輪流載入不同的Fragment,顯示不同的介面,效果如下:

開始的是沒有載入Fragmen為空白:


點擊菜單的NEXT FRAGMENT VIEW,就進入下一個介面,載入兩個:


繼續點擊顯示Fragment 1:


繼續點擊,顯示Fragment2:


然後就是迴圈了:



如此迴圈顯示不同畫面。

一 首先實現這一效果的關鍵代碼,就是在菜單響應函數中輸入如下代碼:

@Overridepublic boolean onOptionsItemSelected(MenuItem item) {int id = item.getItemId();switch (id) {case R.id.next_fragment_view_menu_item: {FragmentManager fragManager = getFragmentManager();FragmentTransaction fragTrans = fragManager.beginTransaction();if (0 == turnNum) {Fragment1 frag1 = new Fragment1();Fragment2 frag2 = new Fragment2();fragTrans.replace(R.id.frame_layout1, frag1);fragTrans.replace(R.id.frame_layout2, frag2);} else if (1 == turnNum) {Fragment1 frag1 = new Fragment1();Fragment frag2 = fragManager.findFragmentById(R.id.frame_layout2);fragTrans.replace(R.id.frame_layout1, frag1);if (frag2 != null) fragTrans.remove(frag2);} else if (2 == turnNum) {Fragment frag1 = fragManager.findFragmentById(R.id.frame_layout1);Fragment2 frag2 = new Fragment2();if (frag1 != null) fragTrans.remove(frag1);fragTrans.replace(R.id.frame_layout2, frag2);}turnNum++;if (turnNum > 2) turnNum = 0;fragTrans.addToBackStack(null);fragTrans.commit();return true;}}return super.onOptionsItemSelected(item);}



1 FragmentManager 是管理所有Fragment的類,故此尋找已有的Fragment使用函數: Fragment frag2 = fragManager.findFragmentByI(R.id.framelayout2);注意要判斷是否取回Fragment,如果沒有那麼frag2 == null。

2 FragmentTransaction管理Fragment變更事務,所有動作,如例子中的remove, replace,都必須是在beginTransaction()和commit()之間才會生效,重複調用commit而沒有調用beginTransaction會程式崩潰的。

3 addToBackStack(null),就是手動把Fragment放在棧中,這樣可以使用back按鍵退回上一層的Fragment安排。Activity是自動放到棧中的。

4 簡單邏輯:turnNum是全域變數,根據這個turnNum的值的不同使用不同的Fragment。

二 主介面的xml如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="bill.su.fragment.MainActivity"    android:orientation="horizontal"    android:id="@+id/linear_fragment"    android:baselineAligned="false" >    <FrameLayout        android:id="@+id/frame_layout1"        android:layout_weight="1"        android:layout_width="0sp"        android:layout_height="match_parent" />    <FrameLayout        android:id="@+id/frame_layout2"        android:layout_weight="1"        android:layout_width="0sp"        android:layout_height="match_parent" /></LinearLayout>

兩個FrameLayout用來裝Fragment


三 菜單res/menu/main.xml的代碼:

<menu xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    tools:context="bill.su.fragment.MainActivity" >    <item         android:id="@+id/next_fragment_view_menu_item"        android:showAsAction="always"        android:title="@string/next_fragment_view_menu_item" /></menu>

四 測試Fragment生命期的全部代碼:

package bill.su.fragment;import android.app.Activity;import android.app.Fragment;import android.os.Bundle;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class Fragment1 extends Fragment {private final String TAG = "FRAGMENTTAG1";@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {Log.d(TAG, "onCreateView called");return inflater.inflate(R.layout.fragment1, container, false);}@Overridepublic void onAttach(Activity activity){super.onAttach(activity);Log.d(TAG, "onAttach called");}@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);Log.d(TAG, "onCreate called");}@Overridepublic void onActivityCreated(Bundle savedInstanceState){super.onActivityCreated(savedInstanceState);Log.d(TAG, "onActivityCreted called");}@Overridepublic void onStart(){super.onStart();Log.d(TAG, "onStart called");}@Overridepublic void onResume() {super.onResume();Log.d(TAG, "onResume called");}@Overridepublic void onPause() {super.onPause();Log.d(TAG, "onPause called");}@Overridepublic void onStop(){super.onStop();Log.d(TAG, "onStop called");}@Overridepublic void onDestroyView() {super.onDestroyView();Log.d(TAG, "onDestroyView called");}@Overridepublic void onDestroy() {super.onDestroy();Log.d(TAG, "onDestroy called");}@Overridepublic void onDetach() {super.onDetach();Log.d(TAG, "onDetach called");}}

主要和Activity不同的是:

onAttached() : Fragment和Activity接起來的是調用

onCreateView(): Fragment的View建立

onActivityCreated():當Activity的onCreate()調用的時候調用

onDestroyView(): 當Fragment的view刪除的時候調用

onDetach(): Fragment從Activity中去掉的是調用




Android百議程序: Fragment動態管理和生命期

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.