1. 程式人生 > >Android Fragment 真正的完全解析(下)

Android Fragment 真正的完全解析(下)

上篇部落格中已經介紹了Fragment產生原因,以及一些基本的用法和各種API,如果你還不瞭解,請看:Android Fragment 真正的完全解析(上)。

本篇將介紹上篇部落格提到的:如何管理Fragment回退棧,Fragment如何與Activity互動,Fragment與Activity互動的最佳實踐,沒有檢視的Fragment的用處,使用Fragment建立對話方塊,如何與ActionBar,MenuItem整合等~~

1、管理Fragment回退棧

類似與Android系統為Activity維護一個任務棧,我們也可以通過Activity維護一個回退棧來儲存每次Fragment事務發生的變化。如果你將Fragment任務新增到回退棧,當用戶點選後退按鈕時,將看到上一次的儲存的Fragment。一旦Fragment完全從後退棧中彈出,使用者再次點選後退鍵,則退出當前Activity。

看這樣一個效果圖:


點選第一個按鈕,切換到第二個介面,點選第二個按鈕,切換到第三個介面,然後點選Back鍵依次回退。這像不像初學Android時的Activity跳轉,當然了,這裡肯定不是,不然我就跪了。這裡是Fragment實現的,使用者點選Back,實際是Fragment回退棧不斷的彈棧。

如何新增一個Fragment事務到回退棧:

FragmentTransaction.addToBackStack(String)

下面講解程式碼:很明顯一共是3個Fragment和一個Activity.

先看Activity的佈局檔案:

  1. <RelativeLayoutxmlns:android
    ="http://schemas.android.com/apk/res/android"
  2.     xmlns:tools="http://schemas.android.com/tools"
  3.     android:layout_width="match_parent"
  4.     android:layout_height="match_parent">
  5.     <FrameLayout
  6.         android:id="@+id/id_content"
  7.         android:layout_width="fill_parent"
  8.         android:layout_height="fill_parent"
    >
  9.     </FrameLayout>
  10. </RelativeLayout>
不同的Fragment就在這個FrameLayout中顯示。

MainActivity.java

  1. package com.zhy.zhy_fragments;  
  2. import android.app.Activity;  
  3. import android.app.FragmentManager;  
  4. import android.app.FragmentTransaction;  
  5. import android.os.Bundle;  
  6. import android.view.Window;  
  7. publicclass MainActivity extends Activity  
  8. {  
  9.     @Override
  10.     protectedvoid onCreate(Bundle savedInstanceState)  
  11.     {  
  12.         super.onCreate(savedInstanceState);  
  13.         requestWindowFeature(Window.FEATURE_NO_TITLE);  
  14.         setContentView(R.layout.activity_main);  
  15.         FragmentManager fm = getFragmentManager();  
  16.         FragmentTransaction tx = fm.beginTransaction();  
  17.         tx.add(R.id.id_content, new FragmentOne(),"ONE");  
  18.         tx.commit();  
  19.     }  
  20. }  
很簡單,直接將FragmentOne新增到佈局檔案中的FrameLayout中,注意這裡並沒有呼叫FragmentTransaction.addToBackStack(String),因為我不喜歡在當前顯示時,點選Back鍵出現白板。而是正確的相應Back鍵,即退出我們的Activity.

下面是FragmentOne

  1. package com.zhy.zhy_fragments;  
  2. import android.app.Fragment;  
  3. import android.app.FragmentManager;  
  4. import android.app.FragmentTransaction;  
  5. import android.os.Bundle;  
  6. import android.view.LayoutInflater;  
  7. import android.view.View;  
  8. import android.view.View.OnClickListener;  
  9. import android.view.ViewGroup;  
  10. import android.widget.Button;  
  11. publicclass FragmentOne extends Fragment implements OnClickListener  
  12. {  
  13.     private Button mBtn;  
  14.     @Override
  15.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  16.             Bundle savedInstanceState)  
  17.     {  
  18.         View view = inflater.inflate(R.layout.fragment_one, container, false);  
  19.         mBtn = (Button) view.findViewById(R.id.id_fragment_one_btn);  
  20.         mBtn.setOnClickListener(this);  
  21.         return view;  
  22.     }  
  23.     @Override
  24.     publicvoid onClick(View v)  
  25.     {  
  26.         FragmentTwo fTwo = new FragmentTwo();  
  27.         FragmentManager fm = getFragmentManager();  
  28.         FragmentTransaction tx = fm.beginTransaction();  
  29.         tx.replace(R.id.id_content, fTwo, "TWO");  
  30.         tx.addToBackStack(null);  
  31.         tx.commit();  
  32.     }  
  33. }  

我們在點選FragmentOne中的按鈕時,使用了replace方法,如果你看了前一篇部落格,一定記得replace是remove和add的合體,並且如果不新增事務到回退棧,前一個Fragment例項會被銷燬。這裡很明顯,我們呼叫tx.addToBackStack(null);將當前的事務新增到了回退棧,所以FragmentOne例項不會被銷燬,但是檢視層次依然會被銷燬,即會呼叫onDestoryView和onCreateView,證據就是:仔細看上面的效果圖,我們在跳轉前在文字框輸入的內容,在使用者Back得到第一個介面的時候不見了。

接下來FragmentTwo

  1. package com.zhy.zhy_fragments;  
  2. import android.app.Fragment;  
  3. import android.app.FragmentManager;  
  4. import android.app.FragmentTransaction;  
  5. import android.os.Bundle;  
  6. import android.view.LayoutInflater;  
  7. import android.view.View;  
  8. import android.view.View.OnClickListener;  
  9. import android.view.ViewGroup;  
  10. import android.widget.Button;  
  11. publicclass FragmentTwo extends Fragment implements OnClickListener  
  12. {  
  13.     private Button mBtn ;  
  14.     @Override
  15.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  16.             Bundle savedInstanceState)  
  17.     {  
  18.         View view = inflater.inflate(R.layout.fragment_two, container, false);  
  19.         mBtn = (Button) view.findViewById(R.id.id_fragment_two_btn);  
  20.         mBtn.setOnClickListener(this);  
  21.         return view ;   
  22.     }  
  23.     @Override
  24.     publicvoid onClick(View v)  
  25.     {  
  26.         FragmentThree fThree = new FragmentThree();  
  27.         FragmentManager fm = getFragmentManager();  
  28.         FragmentTransaction tx = fm.beginTransaction();  
  29.         tx.hide(this);  
  30.         tx.add(R.id.id_content , fThree, "THREE");  
  31. //      tx.replace(R.id.id_content, fThree, "THREE");
  32.         tx.addToBackStack(null);  
  33.         tx.commit();  
  34.     }  
  35. }  

這裡點選時,我們沒有使用replace,而是先隱藏了當前的Fragment,然後添加了FragmentThree的例項,最後將事務新增到回退棧。這樣做的目的是為了給大家提供一種方案:如果不希望檢視重繪該怎麼做,請再次仔細看效果圖,我們在FragmentTwo的EditText填寫的內容,使用者Back回來時,資料還在~~~

最後FragmentThree就是簡單的Toast了:

  1. package com.zhy.zhy_fragments;  
  2. import android.app.Fragment;  
  3. import android.os.Bundle;  
  4. import android.view.LayoutInflater;  
  5. import android.view.View;  
  6. import android.view.View.OnClickListener;  
  7. import android.view.ViewGroup;  
  8. import android.widget.Button;  
  9. import android.widget.Toast;  
  10. publicclass FragmentThree extends Fragment implements OnClickListener  
  11. {  
  12.     private Button mBtn;  
  13.     @Override
  14.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  15.             Bundle savedInstanceState)  
  16.     {  
  17.         View view = inflater.inflate(R.layout.fragment_three, container, false);  
  18.         mBtn = (Button) view.findViewById(R.id.id_fragment_three_btn);  
  19.         mBtn.setOnClickListener(this);  
  20.         return view;  
  21.     }  
  22.     @Override
  23.     publicvoid onClick(View v)  
  24.     {  
  25.         Toast.makeText(getActivity(), " i am a btn in Fragment three",  
  26.                 Toast.LENGTH_SHORT).show();  
  27.     }  
  28. }  

好了,經過上面的介紹,應該已經知道Fragment回退棧是怎麼一回事了,以及hide,replace等各自的應用的場景。

這裡極其注意一點:上面的整體程式碼不具有任何參考價值,純粹為了顯示回退棧,在後面講解了Fragment與Activity通訊以後,會重構上面的程式碼!

2、Fragment與Activity通訊

因為所有的Fragment都是依附於Activity的,所以通訊起來並不複雜,大概歸納為:

a、如果你Activity中包含自己管理的Fragment的引用,可以通過引用直接訪問所有的Fragment的public方法

b、如果Activity中未儲存任何Fragment的引用,那麼沒關係,每個Fragment都有一個唯一的TAG或者ID,可以通過getFragmentManager.findFragmentByTag()或者findFragmentById()獲得任何Fragment例項,然後進行操作。

c、在Fragment中可以通過getActivity得到當前繫結的Activity的例項,然後進行操作。

注:如果在Fragment中需要Context,可以通過呼叫getActivity(),如果該Context需要在Activity被銷燬後還存在,則使用getActivity().getApplicationContext()。

3、Fragment與Activity通訊的最佳實踐

因為要考慮Fragment的重複使用,所以必須降低Fragment與Activity的耦合,而且Fragment更不應該直接操作別的Fragment,畢竟Fragment操作應該由它的管理者Activity來決定。

下面我通過兩種方式的程式碼,分別重構,FragmentOne和FragmentTwo的點選事件,以及Activity對點選事件的響應:

首先看FragmentOne

  1. package com.zhy.zhy_fragments;  
  2. import android.app.Fragment;  
  3. import android.os.Bundle;  
  4. import android.view.LayoutInflater;  
  5. import android.view.View;  
  6. import android.view.View.OnClickListener;  
  7. import android.view.ViewGroup;  
  8. import android.widget.Button;  
  9. publicclass FragmentOne extends Fragment implements OnClickListener  
  10. {  
  11.     private Button mBtn;  
  12.     /** 
  13.      * 設定按鈕點選的回撥 
  14.      * @author zhy 
  15.      * 
  16.      */
  17.     publicinterface FOneBtnClickListener  
  18.     {  
  19.         void onFOneBtnClick();  
  20.     }  
  21.     @Override
  22.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  23.             Bundle savedInstanceState)  
  24.     {  
  25.         View view = inflater.inflate(R.layout.fragment_one, container, false);  
  26.         mBtn = (Button) view.findViewById(R.id.id_fragment_one_btn);  
  27.         mBtn.setOnClickListener(this);  
  28.         return view;  
  29.     }  
  30.     /** 
  31.      * 交給宿主Activity處理,如果它希望處理 
  32.      */
  33.     @Override
  34.     publicvoid onClick(View v)  
  35.     {  
  36.         if (getActivity() instanceof FOneBtnClickListener)  
  37.         {  
  38.             ((FOneBtnClickListener) getActivity()).onFOneBtnClick();  
  39.         }  
  40.     }  
  41. }  

可以看到現在的FragmentOne不和任何Activity耦合,任何Activity都可以使用;並且我們聲明瞭一個介面,來回調其點選事件,想要管理其點選事件的Activity實現此介面就即可。可以看到我們在onClick中首先判斷了當前繫結的Activity是否實現了該介面,如果實現了則呼叫。

再看FragmentTwo

  1. package com.zhy.zhy_fragments;  
  2. import android.app.Fragment;  
  3. import android.os.Bundle;  
  4. import android.view.LayoutInflater;  
  5. import android.view.View;  
  6. import android.view.View.OnClickListener;  
  7. import android.view.ViewGroup;  
  8. import android.widget.Button;  
  9. publicclass FragmentTwo extends Fragment implements OnClickListener  
  10. {  
  11.     private Button mBtn ;  
  12.     private FTwoBtnClickListener fTwoBtnClickListener ;  
  13.     publicinterface FTwoBtnClickListener  
  14.     {  
  15.         void onFTwoBtnClick();  
  16.     }  
  17.     //設定回撥介面
  18.     publicvoid setfTwoBtnClickListener(FTwoBtnClickListener fTwoBtnClickListener)  
  19.     {  
  20.         this.fTwoBtnClickListener = fTwoBtnClickListener;  
  21.     }  
  22.     @Override
  23.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  24.             Bundle savedInstanceState)  
  25.     {  
  26.         View view = inflater.inflate(R.layout.fragment_two, container, false);  
  27.         mBtn = (Button) view.findViewById(R.id.id_fragment_two_btn);  
  28.         mBtn.setOnClickListener(this);  
  29.         return view ;   
  30.     }  
  31.     @Override
  32.     publicvoid onClick(View v)  
  33.     {  
  34.         if(fTwoBtnClickListener != null)  
  35.         {  
  36.             fTwoBtnClickListener.onFTwoBtnClick();  
  37.         }  
  38.     }  
  39. }  

與FragmentOne極其類似,但是我們提供了setListener這樣的方法,意味著Activity不僅需要實現該介面,還必須顯示呼叫mFTwo.setfTwoBtnClickListener(this)。

最後看Activity :

  1. package com.zhy.zhy_fragments;  
  2. import android.app.Activity;  
  3. import android.app.FragmentManager;  
  4. import android.app.FragmentTransaction;  
  5. import android.os.Bundle;  
  6. import android.view.Window;  
  7. import com.zhy.zhy_fragments.FragmentOne.FOneBtnClickListener;  
  8. import com.zhy.zhy_fragments.FragmentTwo.FTwoBtnClickListener;  
  9. publicclass MainActivity extends Activity implements FOneBtnClickListener,  
  10.         FTwoBtnClickListener  
  11. {  
  12.     private FragmentOne mFOne;  
  13.     private FragmentTwo mFTwo;  
  14.     private FragmentThree mFThree;  
  15.     @Override
  16.     protectedvoid onCreate(Bundle savedInstanceState)  
  17.     {  
  18.         super.onCreate(savedInstanceState);  
  19.         requestWindowFeature(Window.FEATURE_NO_TITLE);  
  20.         setContentView(R.layout.activity_main);  
  21.         mFOne = new FragmentOne();  
  22.         FragmentManager fm = getFragmentManager();  
  23.         FragmentTransaction tx = fm.beginTransaction();  
  24.         tx.add(R.id.id_content, mFOne, "ONE");  
  25.         tx.commit();  
  26.     }  
  27.     /** 
  28.      * FragmentOne 按鈕點選時的回撥 
  29.      */
  30.     @Override
  31.     publicvoid onFOneBtnClick()  
  32.     {  
  33.         if (mFTwo == null)  
  34.         {  
  35.             mFTwo = new FragmentTwo();  
  36.             mFTwo.setfTwoBtnClickListener(this);  
  37.         }  
  38.         FragmentManager fm = getFragmentManager();  
  39.         FragmentTransaction tx = fm.beginTransaction();  
  40.         tx.replace(R.id.id_content, mFTwo, "TWO");  
  41.         tx.addToBackStack(null);  
  42.         tx.commit();  
  43.     }  
  44.     /** 
  45.      * FragmentTwo 按鈕點選時的回撥 
  46.      */
  47.     @Override
  48.     publicvoid onFTwoBtnClick()  
  49.     {  
  50.         if (mFThree == null)  
  51.         {  
  52.             mFThree = new FragmentThree();  
  53.         }  
  54.         FragmentManager fm = getFragmentManager();  
  55.         FragmentTransaction tx = fm.beginTransaction();  
  56.         tx.hide(mFTwo);  
  57.         tx.add(R.id.id_content, mFThree, "THREE");  
  58.         // tx.replace(R.id.id_content, fThree, "THREE");
  59.         tx.addToBackStack(null);  
  60.         tx.commit();  
  61.     }  
  62. }  

程式碼重構結束,與開始的效果一模一樣。上面兩種通訊方式都是值得推薦的,隨便選擇一種自己喜歡的。這裡再提一下:雖然Fragment和Activity可以通過getActivity與findFragmentByTag或者findFragmentById,進行任何操作,甚至在Fragment裡面操作另外的Fragment,但是沒有特殊理由是絕對不提倡的。Activity擔任的是Fragment間類似匯流排一樣的角色,應當由它決定Fragment如何操作。另外雖然Fragment不能響應Intent開啟,但是Activity可以,Activity可以接收Intent,然後根據引數判斷顯示哪個Fragment。
4、如何處理執行時配置發生變化

這裡提一下:很多人覺得強制設定螢幕的方向就可以了,但是有一點,當你的應用被至於後臺(例如使用者點選了home),長時間沒有返回的時候,你的應用也會被重新啟動。比如上例:如果你把上面的例子你至於FragmentThree介面,然後處於後臺狀態,長時間後你會發現當你再次通過home開啟時,上面FragmentThree與FragmentOne疊加在一起,這就是因為你的Activity重新啟動,在原來的FragmentThree上又繪製了一個FragmentOne。

好了,下面看一段程式碼:

Activity:

  1. package com.zhy.zhy_fragments;  
  2. import android.app.Activity;  
  3. import android.app.FragmentManager;  
  4. import android.app.FragmentTransaction;  
  5. import android.os.Bundle;  
  6. import android.view.Window;  
  7. publicclass MainActivity extends Activity  
  8. {  
  9.     private FragmentOne mFOne;  
  10.     @Override
  11.     protectedvoid onCreate(Bundle savedInstanceState)  
  12.     {  
  13.         super.onCreate(savedInstanceState);  
  14.         requestWindowFeature(Window.FEATURE_NO_TITLE);  
  15.         setContentView(R.layout.activity_main);  
  16.         mFOne = new FragmentOne();  
  17.         FragmentManager fm = getFragmentManager();  
  18.         FragmentTransaction tx = fm.beginTransaction();  
  19.         tx.add(R.id.id_content, mFOne, "ONE");  
  20.         tx.commit();  
  21.     }  
  22. }  

Fragment
  1. package com.zhy.zhy_fragments;  
  2. import android.app.Fragment;  
  3. import android.os.Bundle;  
  4. import android.util.Log;  
  5. import android.view.LayoutInflater;  
  6. import android.view.View;  
  7. import android.view.ViewGroup;  
  8. publicclass FragmentOne extends Fragment  
  9. {  
  10.     privatestaticfinal String TAG = "FragmentOne";  
  11.     @Override
  12.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  13.             Bundle savedInstanceState)  
  14.     {  
  15.         Log.e(TAG, "onCreateView");  
  16.         View view = inflater.inflate(R.layout.fragment_one, container, false);  
  17.         return view;  
  18.     }  
  19.     @Override
  20.     publicvoid onCreate(Bundle savedInstanceState)  
  21.     {  
  22.         // TODO Auto-generated method stub
  23.         super.onCreate(savedInstanceState);  
  24.         Log.e(TAG, "onCreate");  
  25.     }  
  26.     @Override
  27.     publicvoid onDestroyView()  
  28.     {  
  29.         // TODO Auto-generated method stub
  30.         super.onDestroyView();  
  31.         Log.e(TAG, "onDestroyView");  
  32.     }  
  33.     @Override
  34.     publicvoid onDestroy()  
  35.     {  
  36.         // TODO Auto-generated method stub
  37.         super.onDestroy();  
  38.         Log.e(TAG, "onDestroy");  
  39.     }  
  40. }  

很簡單的程式碼,當你執行之後,不斷的旋轉螢幕,你會發現每旋轉一次螢幕,螢幕上就多了一個FragmentOne的例項,並且後臺log會打印出許多套生命週期的回撥。

類似:

  1. 07-20 08:18:46.651: E/FragmentOne(1633): onCreate  
  2. 07-20 08:18:46.651: E/FragmentOne(1633): onCreate  
  3. 07-20 08:18:46.651: E/FragmentOne(1633): onCreate  
  4. 07-20 08:18:46.681: E/FragmentOne(1633): onCreateView  
  5. 07-20 08:18:46.831: E/FragmentOne(1633): onCreateView  
  6. 07-20 08:18:46.891: E/FragmentOne(1633): onCreateView  

這是為什麼呢,因為當螢幕發生旋轉,Activity發生重新啟動,預設的Activity中的Fragment也會跟著Activity重新建立;這樣造成當旋轉的時候,本身存在的Fragment會重新啟動,然後當執行Activity的onCreate時,又會再次例項化一個新的Fragment,這就是出現的原因。

那麼如何解決呢:

其實通過檢查onCreate的引數Bundle savedInstanceState就可以判斷,當前是否發生Activity的重新建立:

預設的savedInstanceState會儲存一些資料,包括Fragment的例項:通過列印可以看出:

  1. 07-2008:23:12.952: E/FragmentOne(1782): Bundle[{android:fragments=android.app.FragmentManagerState@40d0b7b8, android:viewHierarchyState=Bundle[{android:focusedViewId=2131230721, android:views=android.util.SparseArray@40d0af68}]}]  
所以,我們簡單改一下程式碼,只有在savedInstanceState==null時,才進行建立Fragment例項:
  1. package com.zhy.zhy_fragments;  
  2. import android.app.Activity;  
  3. import android.app.FragmentManager;  
  4. import android.app.FragmentTransaction;  
  5. import android.os.Bundle;  
  6. import android.util.Log;  
  7. import android.view.Window;  
  8. publicclass MainActivity extends Activity  
  9. {  
  10.     privatestaticfinal String TAG = "FragmentOne";  
  11.     private FragmentOne mFOne;  
  12.     @Override
  13.     protectedvoid onCreate(Bundle savedInstanceState)  
  14.     {  
  15.         super.onCreate(savedInstanceState);  
  16.         requestWindowFeature(Window.FEATURE_NO_TITLE);  
  17.         setContentView(R.layout.activity_main);  
  18.         Log.e(TAG, savedInstanceState+"");  
  19.         if(savedInstanceState == null)  
  20.         {  
  21.             mFOne = new FragmentOne();  
  22.             FragmentManager fm = getFragmentManager();  
  23.             FragmentTransaction tx = fm.beginTransaction();  
  24.             tx.add(R.id.id_content, mFOne, "ONE");  
  25.             tx.commit();  
  26.         }  
  27.     }  
  28. }  

現在無論進行多次旋轉都只會有一個Fragment例項在Activity中。

現在還存在一個問題,就是重新繪製時,Fragment發生重建,原本的資料如何保持?

其實和Activity類似,Fragment也有onSaveInstanceState的方法,在此方法中進行儲存資料,然後在onCreate或者onCreateView或者onActivityCreated進行恢復都可以。

由於篇幅原因,就不貼測試程式碼了。

5、Fragmeny與ActionBar和MenuItem整合

Fragment可以新增自己的MenuItem到Activity的ActionBar或者可選選單中。

a、在Fragment的onCreate中呼叫setHasOptionsMenu(true);

b、然後在Fragment子類中實現onCreateOptionsMenu

c、如果希望在Fragment中處理MenuItem的點選,也可以實現onOptionsItemSelected;當然了Activity也可以直接處理該MenuItem的點選事件。

程式碼:

Fragment

  1. package com.zhy.zhy_fragments;  
  2. import android.app.Fragment;  
  3. import android.os.Bundle;  
  4. import android.view.LayoutInflater;  
  5. import android.view.Menu;  
  6. import android.view.MenuInflater;  
  7. import android.view.MenuItem;  
  8. import android.view.View;  
  9. import android.view.ViewGroup;  
  10. import android.widget.Toast;  
  11. publicclass FragmentOne extends Fragment  
  12. {  
  13.     @Override
  14.     publicvoid onCreate(Bundle savedInstanceState)  
  15.     {  
  16.         super.onCreate(savedInstanceState);  
  17.         setHasOptionsMenu(true);  
  18.     }  
  19.     @Override
  20.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  21.             Bundle savedInstanceState)  
  22.     {  
  23.         View view = inflater.inflate(R.layout.fragment_one, container, false);  
  24.         return view;  
  25.     }  
  26.     @Override
  27.     publicvoid onCreateOptionsMenu(Menu menu, MenuInflater inflater)  
  28.     {  
  29.         inflater.inflate(R.menu.fragment_menu, menu);  
  30.     }  
  31.     @Override
  32.     publicboolean onOptionsItemSelected(MenuItem item)  
  33.     {  
  34.         switch (item.getItemId())  
  35.         {  
  36.         case R.id.id_menu_fra_test:  
  37.             Toast.makeText(getActivity(), "FragmentMenuItem1", Toast.LENGTH_SHORT).show();  
  38.             break;  
  39.         }  
  40.         returntrue;  
  41.     }  
  42. }  

Activity
  1. package com.zhy.zhy_fragments;  
  2. import android.app.Activity;  
  3. import android.app.FragmentManager;  
  4. import android.app.FragmentTransaction;  
  5. import android.os.Bundle;  
  6. import android.util.Log;  
  7. import android.view.Menu;  
  8. import android.view.MenuItem;  
  9. import android.view.Window;  
  10. import android.widget.Toast;  
  11. publicclass MainActivity extends Activity  
  12. {  
  13.     privatestaticfinal String TAG = "FragmentOne";  
  14.     private FragmentOne mFOne;  
  15.     @Override
  16.     protectedvoid onCreate(Bundle savedInstanceState)  
  17.     {  
  18.         super.onCreate(savedInstanceState);  
  19.         requestWindowFeature(Window.FEATURE_NO_TITLE);  
  20.         setContentView(R.layout.activity_main);  
  21.         Log.e(TAG, savedInstanceState + "");  
  22.         if (savedInstanceState == null)  
  23.         {  
  24.             mFOne = new FragmentOne();  
  25.             FragmentManager fm = getFragmentManager();  
  26.             FragmentTransaction tx = fm.beginTransaction();  
  27.             tx.add(R.id.id_content, mFOne, "ONE");  
  28.             tx.commit();  
  29.         }  
  30.     }  
  31.     @Override
  32.     publicboolean onCreateOptionsMenu(Menu menu)  
  33.     {  
  34.         super.onCreateOptionsMenu(menu);  
  35.         getMenuInflater().inflate(R.menu.main, menu);  
  36.         returntrue;  
  37.     }  
  38.     @Override
  39.     publicboolean onOptionsItemSelected(MenuItem item)  
  40.     {  
  41.         switch (item.getItemId())  
  42.         {  
  43.         case R.id.action_settings:  
  44.             Toast.makeText(this"setting", Toast.LENGTH_SHORT).show();  
  45.             returntrue;  
  46.         default:  
  47.             //如果希望Fragment自己處理MenuItem點選事件,一定不要忘了呼叫super.xxx
  48.             returnsuper.onOptionsItemSelected(item);  
  49.         }  
  50.     }  
  51. }  

效果圖:

好了,可以很好的看到,Fragment可以新增MenuItem,也可以自己處理點選~~~

6、沒有佈局的Fragment的作用

沒有佈局檔案Fragment實際上是為了儲存,當Activity重啟時,儲存大量資料準備的

7、使用Fragment建立對話方塊

相關推薦

Android Fragment 真正完全解析

上篇部落格中已經介紹了Fragment產生原因,以及一些基本的用法和各種API,如果你還不瞭解,請看:Android Fragment 真正的完全解析(上)。 本篇將介紹上篇部落格提到的:如何管理Fragment回退棧,Fragment如何與Activity互動,Frag

Android N App分屏模式完全解析

在上篇中,介紹了什麼是App分屏模式,以及如何設定我們的App來進入分屏模式。這次我們看一下,作為開發者,我們應該如何讓自己的App進入分屏模式,當App進入分屏模式時,我們注意哪些問題。 簡單地說,我認為除了保證分屏時App功能、效能正常以外,我們需要重點學習 如何在分屏模式下開啟新的Activity 以

Android安全攻防戰,反編譯與混淆技術完全解析

http://blog.csdn.net/guolin_blog/article/details/50451259 http://blog.csdn.net/guolin_blog/article/details/50451259 http://blog.csdn

Android Fragment 真正完全解析

watermark 展示 near 主界面 ddt comm 講解 超級 pro 版權聲明:本文為博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/lmj623565791/article/details/37970961 轉載請標明出處:

Android Fragment 真正完全解析

自從Fragment出現,曾經有段時間,感覺大家談什麼都能跟Fragment談上關係,做什麼都要問下Fragment能實現不~~~哈哈,是不是有點過~~~ 本篇部落格力求為大家說明Fragment如何產生,什麼是Fragment,Fragment生命週期,如何靜態和動態的使用Fragment,Fra

Android Fragment 從原始碼的角度去解析

1.概述   上一篇部落格已經簡單的講了一下Fragment的使用並寫了一個基本的例項,接下來就將其整合到專案中。附視訊地址:http://pan.baidu.com/s/1mhUus56          2.效果實現    

Android 屬性動畫Property Animation 完全解析 【轉】

轉載請標明出處:http://blog.csdn.net/lmj623565791/article/details/38067475 1、概述 Android提供了幾種動畫型別:View Animation 、Drawable Animation 、Property Anima

Android自助餐】Handler訊息機制完全解析MessageQueue的佇列管理

Android自助餐Handler訊息機制完全解析(二)MessageQueue的佇列管理 Android自助餐Handler訊息機制完全解析二MessageQueue的佇列管理 新增到訊息佇列enqueueMessage 從佇

Android自助餐】Handler訊息機制完全解析鳥瞰與總結

Android自助餐Handler訊息機制完全解析(五)鳥瞰與總結 Android自助餐Handler訊息機制完全解析五鳥瞰與總結 Message MessageQueue Handler Looper

Android自助餐】Handler訊息機制完全解析Looper解析

Android自助餐Handler訊息機制完全解析(四)Looper解析 Android自助餐Handler訊息機制完全解析四Looper解析 Looper 初始化prepare 提供loope

Android進階——效能優化之程序拉活原理及手段完全解析

引言 上一篇文章Android進階——效能優化之程序保活原理及手段完全解析(一)總結了Android程序和執行緒的相關知識,主要介紹了幾種提升程序優先順序的手段,通常僅僅是提高優先順序只能讓你的程序存活時間久一點,但是真正的被殺死之後就不會自動拉活的,如果你的程

Android 開源框架Universal-Image-Loader完全解析--- 基本介紹及使用

                大家好!差不多兩個來月沒有寫文章了,前段時間也是在忙換工作的事,準備筆試面試什麼的事情,現在新工作找好了,新工作自己也比較滿意,唯一遺憾的就是自己要去一個新的城市,新的環境新的開始,希望自己能儘快的適應新環境,現在在準備交接的事情,自己也有一些時間了,所以就繼續給大家分享And

Android安全攻防戰,反編譯與混淆技術完全解析

轉載請註明出處:http://blog.csdn.net/guolin_blog/article/details/49738023 之前一直有猶豫過要不要寫這篇文章,畢竟去反編譯人家的程式並不是什麼值得驕傲的事情。不過單純從技術角度上來講,掌握反編譯功能確實是

Android 屬性動畫Property Animation 完全解析

目錄(?)[+] 1、概述 Android提供了幾種動畫型別:View Animation 、Drawable Animation 、Property Animation 。View Animation相當簡單,不過只能支援簡單的縮放、平移、旋轉、透明度基本的動畫,

Android 網路通訊框架Volley完全解析

Volley簡介及Request基本用法  Google I/O 2013上,Volley釋出了。Volley是Android平臺上的網路通訊庫,能使網路通訊更快,更簡單,更健壯。這是Volley名

Android硬編解碼介面MediaCodec使用完全解析

由於4月初要離職了,在找新工作,發現很多企業的招聘資訊都有“附上自己的技術部落格可以加分”類似的說明,正好最後的這段時間會比較閒,所以打算整理一下以前記錄的一些筆記發上來,也算是回顧一下。由於這些筆記或多或少的參考了其他資料,所以本人不擁有其版權,可以隨便

Android 開源框架Universal-Image-Loader完全解析--- 圖片快取策略詳解

本篇文章繼續為大家介紹Universal-Image-Loader這個開源的圖片載入框架,介紹的是圖片快取策略方面的,如果大家對這個開源框架的使用還不瞭解,大家可以看看我之前寫的一篇文章Android 開源框架Universal-Image-Loader完全解析(一)---

android permission許可權與安全機制解析

  剛建了一個QQ群,感興趣的大家一起多多交流:544645972   在android permission許可權與安全機制解析(上)篇部落格中,我已經詳細介紹了android相關係統permission和自定義permission,以及一些許可權機制和安全

Android Activity 完全解析

      在上一篇文章中我們學習了 Activity 的生命週期以及用 Intent 開啟系統的方法相關方面的知識,分析了單個 Activity 生命週期從建立到銷燬的過程,以及多個 Activit

Lambda表達式樹解析

equal arguments provider inf gets 轉換 lis bin text 概述   前面章節,總結了Lambda樹的構建,那麽怎麽解析Lambda表達式樹那?Lambda表達式是一種委托構造而成,如果能夠清晰的解析Lambda表達式樹,那麽就能夠