【Android UI設計與開發】第07期:底部菜單欄(二)Fragment的詳細介紹和使用方法

轉載出處:http://blog.csdn.net/yangyu20121224/article/details/8995025

轉載,請自覺註明!


       

        由於TabActivity在Android4.0以後已經被完全棄用,那麼我就不再浪費口水繼續講解它了,取而代之的是Fragment。Fragment是Android3.0新增的概念,Fragment翻譯成中文是碎片的意思,不過卻和Activity十分的相似,這一篇我花大量的篇幅來詳細的講解Fragment的介紹和使用方法。


一、Fragment的基礎知識介紹


1.1概述


1.1.1 特性


        Fragment是activity的界面中的一部分或一種行爲。可以把多個Fragment組合到一個activity中來創建一個多界面

並且可以在多個activity中重用一個Fragment。可以把Fragment任務模塊化的一段activity,它具有自己的生命週期,

接收它自己的事件,並可以在activity運行時被添加或刪除。

       Fragment不能獨立存在,它必須嵌入到activity中,而且Fragment的生命週期直接受所在的activity的影響。例

如:當activity暫停時,他擁有的所有的Fragment都暫停了,當activity銷燬時,他擁有的所有Fragment都被銷燬。然

而,當activity運行時(在onResume()之後,onPause()之前),可以單獨地操作每個Fragment,比如添加或刪除它

們。當中執行上述針對Fragment的事務時,可以將事務添加到一個棧中,這個棧被activity管理,棧中的每一條都是一

個Fragment的一次事務。有了這個棧,就可以反向執行Fragment的事務,這樣就可以在Fragment級支持“返回”鍵

(向後導航)。

        當向activity中添加一個Fragment時,它須置於ViewGroup控件中,並且需定義Fragment自己的界面。可以在

layout.xml佈局文件中聲明Fragment,元素爲:<fragment>;也可以在代碼中創建Fragment,然後把它加入到

ViewGroup控件中。然而,Fragment不一定非要放在activity的界面中,它可以隱藏在後臺爲activity工作。


1.1.2 生命週期


onCreate():

     當創建fragment時系統調用此方法。在其中必須初始化fragment的基礎組件們。可參考activity的說明;


onCreateView():

     系統在fragment要畫自己的界面時調用(在真正顯示之前)此方法,這個方法必須返回fragment的layout的根控

件,如果這個fragment不提供界面,那它應返回null;


onPause():

     大多數程序應最少對fragment實現這三個方法,當然還有其它幾個回調方法可應該按情況實現之,所有的聲明週期

回調函數在“操控fragment的生命週期”一節中有詳細討論。


下圖爲fragment的生命週期(它所在的activity處於運行狀態)



 Activity和Fragment生命週期對比圖如下:


兩個的生命週期很類似,也息息相關。


1.1.3 派生類


DialogFragment

    顯示一個浮動的對話框。使用這個類創建對話框是替代activity創建對話框的最佳選擇。因爲可以把fragmentdialog

放入到activity的返回棧中,使用戶能再返回到這個對話框。


ListFragment

    顯示一個列表控件,就像ListActivity類,它提供了很多管理列表的方法,比如onListItemClick()方法響應click事件。


PreferenceFragment

    顯示一個由Preference對象組成的列表,與PreferenceActivity相同。它用於爲程序創建“設置”activity。


1.2 範例


     寫一個讀新聞的程序,可以用一個fragment顯示標題列表,另一個fragment顯示選中標題的內容,這兩個fragment

都在一個activity上,並排顯示。那麼這兩個fragment都有自己的生命週期並響應自己感興趣的事件。於是,不需要再

像手機上那樣用一個activity顯示標題列表,用另一個activity顯示新聞內容;現在可以把兩者放在一個activity上同時顯

示出來。如下圖:


         

       Fragment必須被寫成可重用的模塊。因爲fragment有自己的layout,自己進行事件響應,擁有自己的生命週期和

行爲,所以可以在多個activity中包含同一個Fragment的不同實例。這對於讓世界在不同的屏幕尺寸下都能給用戶完美

的體驗尤其重要。比如可以在程序運行於大屏幕中時啓動包含很多fragment的activity,而在運行小屏幕時啓動一個包

含少量fragment的activity。

        剛纔讀新聞的程序,當檢測到程序運行於大屏幕時,啓動activityA,將標題列表和新聞內容這兩個fragment都放

在activityA中;當檢測到程序運行於小屏幕時,還是啓動activityA,但此時A中只有標題列表fragment,當選中一個標

題時,activityA啓動activityB,B中含有新聞內容fragment。


1.3 創建Fragment


         要創建fragment,必須從Fragment或Fragment的派生類派生出一個類。Fragment的代碼寫起來有些像activity。

它具有跟activity一樣的回調方法,比如onCreate(),onStart(),onPause()和onStop()。實際上,如果想把老的程序改爲

使用fragment,基本上只需要把activity的回調方法的代碼移到fragment中對應的方法即可。


1.3.1添加有界面的Fragment


       Fragment一般作爲activity的用戶界面的一部分,把它自己layout嵌入到activity的layout中。一個要爲fragment提

供layout,必須實現onCreateView()回調方法,然後在這個方法中返回一個View對象,這個對象時fragment的layout的

根。

       注意:如果fragment是從ListFragment中派生的,就不需要實現onCreateView()方法了,因爲默認的實現已經返

回了ListView控件對象。

       要從onCreateView()方法中返回layout對象,可以從layout.xml佈局文件中生成layout對象。爲了幫助這樣做,

onCreateView()提供了一個layoutInflater對象。舉例:以下代碼展示了一個Fragment的子類如何從layout.xml佈局文件

example_fragment.xml中生成對象。

[java] view plaincopy
  1. <span style="font-size:10px;">public static ExampleFragment extends Fragment {   
  2. @Override   
  3. publicView onCreateView(LayoutInflater inflater, ViewGroup container,   
  4. Bundle savedInstanceState) {   
  5. returninflater.inflate(R.layout.example_fragment, container, false);   
  6. }   
  7. }</span>  

       

     onCreateView()參數中的container是存放fragment的layout的ViewGroup對象。saveInstanceState參數是一個

Bundle,跟activity的onCreate()中Bundle差不多,用於狀態恢復。但是fragment的onCreate()中也有Bundle參數,所

以此處的Bundle中存放的數據與onCreate()中存放的數據還是不同的。

Inflate()方法中有三個參數:

  <1> layout的資源ID;

  <2> 存放fragment的layout的ViewGroup;

  <3> 布爾數據表示是否在創建fragment的layout期間,把layout附加到container上(在這個例子中,因爲系統已經把layout插入到container中了,所以值爲false,如果爲true會導致在最終的layout中創建多餘的ViewGroup)。

      下面講述如何把它添加到activity中。把fragment添加到activity一般情況下,fragment把它的layout作爲activity的

layout的一部分合併到activity中,有兩種方法將一個fragment添加到activity中:


方法一:在activity的layout.xml文件中聲明fragment

[html] view plaincopy
  1. <?xmlversionxmlversion="1.0" encoding="utf-8" ?>  
  2. <LinearLayoutxmlns:androidLinearLayoutxmlns:android=" http://schemas.android.com/apk/res/android"   
  3. android:orientation="horizontal"   
  4. android:layout_width="match_parent"   
  5. android:layout_height="match_parent" >  
  6. <fragmentandroid:namefragmentandroid:name="com.android.cwj.ArticleListFragment"   
  7. android:id="@+id/list"   
  8. android:layout_weight="1"   
  9. android:layout_width="0dp"   
  10. android:layout_height="match_parent" />  
  11. <fragmentandroid:namefragmentandroid:name="com.android.cwj.ArticleReaderFragment"   
  12. android:id="@+id/viewer"   
  13. android:layout_weight="2"   
  14. android:layout_width="0dp"   
  15. android:layout_height="match_parent" />  
  16. </LinearLayout>  

       以上代碼中,<fragment>中聲明一個fragment。當系統創建上例中的layout時,它實例化每一個fragment,然後調

用它們的onCreateView()方法,以獲取每個fragment的layout。系統把fragment返回的view對象插入到<fragment>元

素的位置,直接代替<fragment>元素。

注:每個fragment都需要提供一個ID,系統在activity重新創建時用它來恢復fragment,也可以用它來操作fragment進

行其它的事物,比如刪除它。有三種方法給fragment提供ID:

  <1> 爲Android:id屬性賦一個數字;

  <2> 爲Android:tag屬性賦一個字符串。

如果沒有使用上述任何一種方法,系統將使用fragment的容器的ID。

方法二:在代碼中添加fragment到一個ViewGroup

        這種方法可以在運行時,把fragment添加到activity的layout中。只需指定一個要包含fragment的ViewGroup。爲

了完成fragment的事務(比如添加,刪除,替換等),必須使用FragmentTransaction的方法。可以從activity獲取

FragmentTransaction,如下:

[java] view plaincopy
  1. FragmentManager fragmentManager = getFragmentManager();  
  2. FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();  

         然後可以用add()方法添加一個fragment,它有參數用於指定容納fragment的ViewGroup。如,Add()的第一個參數

是容器ViewGroup,第二個是要添加的fragment。一旦通過FragmentTransaction對fragment做出了改變,必須調用方

法commit()提交這些改變。不僅在無界面的fragment中,在有界面的fragment中也可以使用tag來作爲唯一的標誌,這

樣在需要獲取fragment對象時,要調用findFragmentTag()。

 

1.3.2 添加沒有界面的Fragment

         上面演示瞭如何添加fragment來提供界面,然而,也可以使用fragment爲activity提供後臺的行爲而不用顯示

fragment的界面。要添加一個沒有界面的fragment,需要在activity中調用方法add(Fragment,String)(它支持用一個唯

一的字符串做爲fragment的“tag”,而不是viewID)。這樣添加的fragment由於沒有界面,所以在實現它時不需要調用

實現onCreateView()方法。

        使用tag字符串來標示一個fragment並不是只能用於沒有界面的fragment上,也可以把它用於有界面的fragment

上,但是,如果一個fragment沒有界面,tag字符串將成爲它唯一的選擇。獲取以tag表示的fragment,需使用方法

findFragmentByTab()。


1.4 Fragment管理

      要管理fragment,需使用FragmentManager,要獲取它,需在activity中調用方法getFragmentManager()。

可以用FragmentManager來做以下事情:

      <1> 使用方法findFragmentById()或findFragmentByTag(),獲取activity中已存在的fragment;

      <2> 使用方法popBackStack()從activity的後退棧中彈出fragment(這可以模擬後退鍵引發的動作),用方法addOnBackStackChangedListenner()註冊一個偵聽器以監視後退棧的變化;

      <3> 還可以使用FragmentManager打開一個FragmentTransaction來執行fragment的事務,比如添加或刪除fragment。

       在activity中使用fragment的一個偉大的好處是能根據用戶的輸入對fragment進行添加、刪除、替換以及執行其他

動作的能力。提交的一組fragment的變化叫做一個事務。事務通過FragmentTransaction來執行。還可以把每個事務保

存在activity的後退棧中,這樣就可以讓用戶在fragment變化之間導航(跟在activity之間導航一樣)。


可以通過FragmentManager來取得FragmentTransaction的實例,如下:

[java] view plaincopy
  1. FragmentManager fragmentManager = getFragmentManager();  
  2. FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();  

 

一個事務是在同一時刻執行的一組動作(很像數據庫中的事務)。可以用add(),remove(),replace()等方法構成事務

,最後使用commit()方法提交事務。在調用commit()之前,可以用addToBackStack()把事務添加到一個後退棧中,這

個後退棧屬於所在的activity。有了它,就可以在用戶按下返回鍵時,返回到fragment執行事務之前的狀態。如下例:

演示瞭如何用一個fragment代替另一個fragment,同時在後退棧中保存被代替的fragment的狀態。

[java] view plaincopy
  1. //創建一個fragment  
  2. Fragment newFragment = new ExampleFragment();  
  3. //實例化fragment事務管理器  
  4. FragmentTransaction transaction = getFragmentManager().beginTransaction();  
  5.   
  6. //用新創建的fragment來代替fragment_container  
  7. transaction.replace(R.id.fragment_container,newFragment);  
  8. //添加進棧中  
  9. transaction.addToBackStack(null);  
  10.   
  11. //提交事務  
  12. transaction.commit();  

       解釋:newFragment代替了控件ID R.id.fragment_container所指向的ViewGroup中所含的任何fragment。然後調

用addToBackStack(),此時被代替的fragment就被放入後退棧中,於是當用戶按下返回鍵時,事務發生回溯,原先的

fragment又回來了。如果向事務添加了多個動作,比如多次調用了add(),remove()等之後又調用了addToBackStack(

)方法,那麼所有的在commit()之前調用的方法都被作爲一個事務。

當用戶按返回鍵時,所有的動作都被反向執行(事務回溯)。

    

事務中動作的執行順序可隨意,但要注意以下幾點:

<1> 必須最後調用commit();
<2> 如果添加了多個fragment,那麼它們的現實順序跟添加順序一致(後顯示的覆蓋前面的)

<3> 如果在執行的事務中有刪除fragment的動作,而且沒有調用addToBackStack(),那麼當事務提交時,那些被刪除

的fragment就被銷燬了。反之,那些fragment就不會被銷燬,而是處於停止狀態。當用戶返回時,它們會被恢復。

<4> 但是,調用commit()後,事務並不會馬上執行。它會在activity的UI線程(其實就是主線程)中等待直到現成能執

行的時候才執行。如果必要,可以在UI線程中調用executePendingTransactions()方法來立即執行事務。但一般不需

要這樣做,除非有其它線程在等待事務的執行。

 

    注意:只能在activity處於可保存狀態的狀態時,比如running中,onPause()方法和onStop()方法中提交事務,否則

會引發異常。這是因爲fragment的狀態會丟失。如果要在可能丟失狀態的情況下提交事務,請使用

commitAllowingStateLoss()。

 

1.5 Fragment與Activity通訊

      

      儘管fragment的實現是獨立於activity的,可以被用於多個activity,但是每個activity所包含的是同一個fragment的

不同的實例。Fragment可以調用getActivity()方法很容易的得到它所在的activity的對象,然後查找activity中的控件

們(findViewById())。         

       有時,可能需要fragment與activity共享事件。一個好辦法是在fragment中定義一個回調接口,然後在activity中實

現之。例如,還是那個新聞程序的例子,它有一個activity,activity中含有兩個fragment。fragmentA顯示新聞標題,

fragmentB現實標題對應的內容。fragmentA必須在用戶選擇了某個標題時告訴activity,然後activity再告訴

fragmentB,fragmentB就顯示出對應的內容。

 

 二、Fragment實例講解一

 

2.1 實例效果圖


點擊“存儲”按鈕顯示的界面:

 

點擊wifi“按鈕”顯示的界面:



2.2 項目結構


 

2.3 具體代碼編寫


1、左邊頁面佈局界面,frag_list.xml:

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="無線和網絡"  
  11.         android:textSize="30sp" />  
  12.   
  13.     <TextView  
  14.         android:layout_width="match_parent"  
  15.         android:layout_height="1px"  
  16.         android:background="@color/lineColor" />  
  17.   
  18.     <LinearLayout  
  19.         android:layout_width="match_parent"  
  20.         android:layout_height="wrap_content"  
  21.         android:layout_gravity="center_vertical"  
  22.         android:layout_marginLeft="10dp"  
  23.         android:orientation="horizontal" >  
  24.   
  25.         <TextView  
  26.             android:id="@+id/wifi"  
  27.             android:layout_width="wrap_content"  
  28.             android:layout_height="wrap_content"  
  29.             android:layout_gravity="center_vertical"  
  30.             android:text="WI-Fi"  
  31.             android:textSize="30sp" />  
  32.   
  33.         <ToggleButton  
  34.             android:id="@+id/toggleButton"  
  35.             android:layout_width="wrap_content"  
  36.             android:layout_height="wrap_content"  
  37.             android:layout_gravity="center_vertical"  
  38.             android:layout_marginLeft="20dp"  
  39.             android:text="開" />  
  40.     </LinearLayout>  
  41.   
  42.     <TextView  
  43.         android:layout_width="match_parent"  
  44.         android:layout_height="1px"  
  45.         android:background="@color/lineColor" />  
  46.   
  47.     <TextView  
  48.         android:layout_width="wrap_content"  
  49.         android:layout_height="wrap_content"  
  50.         android:text="設備"  
  51.         android:textSize="30sp" />  
  52.   
  53.     <TextView  
  54.         android:layout_width="match_parent"  
  55.         android:layout_height="1px"  
  56.         android:background="@color/lineColor" />  
  57.   
  58.     <TextView  
  59.         android:id="@+id/saveBut"  
  60.         android:layout_width="fill_parent"  
  61.         android:layout_height="wrap_content"  
  62.         android:layout_marginLeft="10dp"  
  63.         android:text="存儲"  
  64.         android:textSize="35sp" />  
  65.   
  66. </LinearLayout>  

2、右邊頁面佈局界面,frag_detail.xml:

[html] view plaincopy
  1. <span style="font-size:12px;"><?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:background="@color/right"  
  6.     android:orientation="vertical" >  
  7.   
  8.     <RelativeLayout  
  9.         android:id="@+id/save"  
  10.         android:layout_width="fill_parent"  
  11.         android:layout_height="fill_parent"  
  12.         android:layout_margin="10dp"  
  13.         android:visibility="gone" >  
  14.   
  15.         <include layout="@layout/save" />  
  16.     </RelativeLayout>  
  17.   
  18.     <RelativeLayout  
  19.         android:id="@+id/wifi"  
  20.         android:layout_width="fill_parent"  
  21.         android:layout_height="fill_parent"  
  22.         android:layout_margin="10dp"  
  23.         android:visibility="gone" >  
  24.   
  25.         <include layout="@layout/wifi" />  
  26.     </RelativeLayout>  
  27.   
  28. </LinearLayout></span>  

3、主佈局界面,main.xml:

[html] view plaincopy
  1. <LinearLayout xmlns: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.     android:orientation="horizontal"  
  6.     tools:context=".AndroidFragmentActivity" >  
  7.   
  8.     <!-- 主頁面 -->  
  9.     <!-- 左邊頁面 -->  
  10.   
  11.     <fragment  
  12.         android:id="@+id/frag_list"  
  13.         android:name="co.cm.fragement.FragementList"  
  14.         android:layout_width="fill_parent"  
  15.         android:layout_height="wrap_content"  
  16.         android:layout_weight="2" />  
  17.   
  18.     <!-- 右面頁面 -->  
  19.   
  20.     <fragment  
  21.         android:id="@+id/frag_detail"  
  22.         android:name="co.cm.fragement.FragementDetails"  
  23.         android:layout_width="fill_parent"  
  24.         android:layout_height="wrap_content"  
  25.         android:layout_weight="1" />  
  26.   
  27. </LinearLayout>  

4、list_item.xml:

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:background="@color/left"  
  6.     android:orientation="horizontal" >  
  7.   
  8.     <ImageView  
  9.         android:id="@+id/img"  
  10.         android:layout_width="wrap_content"  
  11.         android:layout_height="wrap_content" />  
  12.   
  13.     <TextView  
  14.         android:id="@+id/txt_title"  
  15.         android:layout_width="wrap_content"  
  16.         android:layout_height="wrap_content"  
  17.         android:text="Large Text"  
  18.         android:textAppearance="?android:attr/textAppearanceLarge" />  
  19.   
  20. </LinearLayout>  

5、save.xml:

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:layout_width="match_parent"  
  9.         android:layout_height="1px"  
  10.         android:background="@color/lineColor" />  
  11.   
  12.     <TextView  
  13.         android:layout_width="wrap_content"  
  14.         android:layout_height="wrap_content"  
  15.         android:layout_marginLeft="10dp"  
  16.         android:text="內部存儲空間"  
  17.         android:textSize="30sp" />  
  18.   
  19.     <TextView  
  20.         android:layout_width="wrap_content"  
  21.         android:layout_height="wrap_content"  
  22.         android:layout_marginBottom="5dp"  
  23.         android:layout_marginLeft="10dp"  
  24.         android:layout_marginTop="5dp"  
  25.         android:text="1GB/1.98GB"  
  26.         android:textSize="20sp" />  
  27.   
  28.     <TextView  
  29.         android:layout_width="match_parent"  
  30.         android:layout_height="1px"  
  31.         android:background="@color/lineColor" />  
  32.   
  33.     <TextView  
  34.         android:layout_width="wrap_content"  
  35.         android:layout_height="wrap_content"  
  36.         android:layout_marginLeft="20dp"  
  37.         android:text="總容量"  
  38.         android:textSize="30sp" />  
  39.   
  40.     <TextView  
  41.         android:layout_width="wrap_content"  
  42.         android:layout_height="wrap_content"  
  43.         android:layout_marginBottom="5dp"  
  44.         android:layout_marginLeft="20dp"  
  45.         android:layout_marginTop="5dp"  
  46.         android:text="1.98GB"  
  47.         android:textSize="20sp" />  
  48.   
  49.     <TextView  
  50.         android:layout_width="match_parent"  
  51.         android:layout_height="1px"  
  52.         android:background="@color/lineColor" />  
  53.   
  54. </LinearLayout>  

6、wifi_list:

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:id="@+id/wifi_name"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="qinjin_tp_2" />  
  12.   
  13.     <LinearLayout  
  14.         android:layout_width="match_parent"  
  15.         android:layout_height="wrap_content"  
  16.         android:orientation="horizontal" >  
  17.   
  18.         <TextView  
  19.             android:layout_width="wrap_content"  
  20.             android:layout_height="wrap_content"  
  21.             android:text="信號強度  :" />  
  22.   
  23.         <TextView  
  24.             android:id="@+id/wifi_name_state"  
  25.             android:layout_width="match_parent"  
  26.             android:layout_height="wrap_content"  
  27.             android:text="還沒有連接" />  
  28.     </LinearLayout>  
  29.   
  30. </LinearLayout>  

7、wifi.xml:

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <LinearLayout  
  8.         android:id="@+id/wifiLinear"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:orientation="vertical" >  
  12.   
  13.         <LinearLayout  
  14.             android:layout_width="match_parent"  
  15.             android:layout_height="wrap_content"  
  16.             android:orientation="vertical" >  
  17.   
  18.             <TextView  
  19.                 android:layout_width="wrap_content"  
  20.                 android:layout_height="wrap_content"  
  21.                 android:text="MAC地址  :"  
  22.                 android:textSize="@dimen/textsize" />  
  23.   
  24.             <TextView  
  25.                 android:id="@+id/mac_address"  
  26.                 android:layout_width="wrap_content"  
  27.                 android:layout_height="wrap_content"  
  28.                 android:text="MAC地址 "  
  29.                 android:textSize="@dimen/textsize" />  
  30.         </LinearLayout>  
  31.   
  32.         <LinearLayout  
  33.             android:layout_width="match_parent"  
  34.             android:layout_height="wrap_content"  
  35.             android:orientation="vertical" >  
  36.   
  37.             <TextView  
  38.                 android:layout_width="wrap_content"  
  39.                 android:layout_height="wrap_content"  
  40.                 android:text="接入點的BSSID :"  
  41.                 android:textSize="@dimen/textsize" />  
  42.   
  43.             <TextView  
  44.                 android:id="@+id/bssid"  
  45.                 android:layout_width="wrap_content"  
  46.                 android:layout_height="wrap_content"  
  47.                 android:text="接入點的BSSID "  
  48.                 android:textSize="@dimen/textsize" />  
  49.         </LinearLayout>  
  50.   
  51.         <LinearLayout  
  52.             android:layout_width="match_parent"  
  53.             android:layout_height="wrap_content"  
  54.             android:orientation="vertical" >  
  55.   
  56.             <TextView  
  57.                 android:layout_width="wrap_content"  
  58.                 android:layout_height="wrap_content"  
  59.                 android:text="IP地址: "  
  60.                 android:textSize="@dimen/textsize" />  
  61.   
  62.             <TextView  
  63.                 android:id="@+id/ip_address"  
  64.                 android:layout_width="wrap_content"  
  65.                 android:layout_height="wrap_content"  
  66.                 android:text="IP地址 "  
  67.                 android:textSize="@dimen/textsize" />  
  68.         </LinearLayout>  
  69.   
  70.         <LinearLayout  
  71.             android:layout_width="match_parent"  
  72.             android:layout_height="wrap_content"  
  73.             android:orientation="vertical" >  
  74.   
  75.             <TextView  
  76.                 android:layout_width="wrap_content"  
  77.                 android:layout_height="wrap_content"  
  78.                 android:text="id  "  
  79.                 android:textSize="@dimen/textsize" />  
  80.   
  81.             <TextView  
  82.                 android:id="@+id/id"  
  83.                 android:layout_width="wrap_content"  
  84.                 android:layout_height="wrap_content"  
  85.                 android:text="id "  
  86.                 android:textSize="@dimen/textsize" />  
  87.         </LinearLayout>  
  88.   
  89.         <LinearLayout  
  90.             android:layout_width="match_parent"  
  91.             android:layout_height="wrap_content"  
  92.             android:orientation="vertical" >  
  93.   
  94.             <TextView  
  95.                 android:layout_width="wrap_content"  
  96.                 android:layout_height="wrap_content"  
  97.                 android:text=" WifiInfo的所有信息包   "  
  98.                 android:textSize="@dimen/textsize" />  
  99.   
  100.             <TextView  
  101.                 android:id="@+id/info"  
  102.                 android:layout_width="wrap_content"  
  103.                 android:layout_height="wrap_content"  
  104.                 android:text="WifiInfo的所有信息包  "  
  105.                 android:textSize="@dimen/textsize" />  
  106.         </LinearLayout>  
  107.   
  108.         <ListView  
  109.             android:id="@+id/listview"  
  110.             android:layout_width="fill_parent"  
  111.             android:layout_height="fill_parent"  
  112.             android:layout_marginBottom="2dp" >  
  113.         </ListView>  
  114.     </LinearLayout>  
  115.   
  116.     <TextView  
  117.         android:id="@+id/wifiText"  
  118.         android:layout_width="wrap_content"  
  119.         android:layout_height="wrap_content"  
  120.         android:layout_centerInParent="true"  
  121.         android:text="要查看可用的網絡,請打開wifi"  
  122.         android:textSize="@dimen/textsize" />  
  123.   
  124. </RelativeLayout>  

8、主界面類,AndroidFragmentActivity.java:

[java] view plaincopy
  1. package co.cm.fragement;  
  2.   
  3. import co.cm.fragement.R;  
  4. import android.app.Activity;  
  5. import android.content.Context;  
  6. import android.os.Bundle;  
  7.   
  8. public class AndroidFragmentActivity extends Activity {  
  9.     // 主activity  
  10.     @Override  
  11.     public void onCreate(Bundle savedInstanceState) {  
  12.         super.onCreate(savedInstanceState);  
  13.         setContentView(R.layout.main);  
  14.         WifiAdmin.getWifiAdmin().setmContext(AndroidFragmentActivity.this);  
  15.         WifiAdmin.getWifiAdmin().getWifiMeathod();  
  16.     }  
  17. }  

9、左面fragment界面類,FragmentList.java:

[java] view plaincopy
  1. package co.cm.fragement;  
  2.   
  3. import co.cm.fragement.R;  
  4.   
  5. import android.app.Fragment;  
  6. import android.os.Bundle;  
  7. import android.os.Handler;  
  8. import android.os.Message;  
  9. import android.util.Log;  
  10. import android.view.LayoutInflater;  
  11. import android.view.View;  
  12. import android.view.View.OnClickListener;  
  13. import android.view.ViewGroup;  
  14. import android.widget.CompoundButton;  
  15. import android.widget.CompoundButton.OnCheckedChangeListener;  
  16. import android.widget.LinearLayout;  
  17. import android.widget.TextView;  
  18. import android.widget.ToggleButton;  
  19.   
  20. /** 
  21.  * @author yuyang 
  22.  *  功能描述:左面fragment界面類,該類提供了選項操作 
  23.  */  
  24. public class FragementList extends Fragment {  
  25.     //點擊切換到wifi存儲界面  
  26.     private TextView wifi;  
  27.       
  28.     //點擊切換到save存儲界面  
  29.     private TextView saveBut;  
  30.       
  31.     //定義右面fragment實例  
  32.     private FragementDetails frag_detail;  
  33.       
  34.     //打開關閉wifi按鈕  
  35.     private ToggleButton toggleButton;  
  36.           
  37.     //toggleButton按鈕是否被點擊  
  38.     private boolean isChecked = false;  
  39.       
  40.     //監聽button狀態線程標誌位  
  41.     private boolean butIsRunning = false;  
  42.   
  43.     @Override  
  44.     public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {  
  45.         // 在這裏初始化fragment的頁面  
  46.         return inflater.inflate(R.layout.frag_list, container, false);  
  47.     }  
  48.   
  49.     @Override  
  50.     public void onActivityCreated(Bundle savedInstanceState) {  
  51.         super.onActivityCreated(savedInstanceState);  
  52.         // 由於fragment不是activity,不是oncreated,而是onActivityCreated  
  53.         setView();  
  54.         setListener();  
  55.   
  56.         startThread();// 啓動控制button的線程,當wifi狀態不是在1或者3的時候,不可點擊,  
  57.         // if (frag != null && frag.isInLayout()) {  
  58.         // switch (arg2) {  
  59.         // case 0:  
  60.         // frag.setText("0000");  
  61.     }  
  62.   
  63.     /** 
  64.      * 給按鈕設置監聽 
  65.      */  
  66.     public void setListener() {   
  67.         saveBut.setOnClickListener(new OnClickListener() {  
  68.             @Override  
  69.             public void onClick(View v) {  
  70.                 frag_detail.setSaveShow();  
  71.             }  
  72.         });  
  73.           
  74.         wifi.setOnClickListener(new OnClickListener() {  
  75.             @Override  
  76.             public void onClick(View v) {  
  77.                 frag_detail.setWifiShow();  
  78.                 Log.i("111", WifiAdmin.getWifiAdmin().checkState() + "===-=-");  
  79.                 checktoggleButton();// 當點回到wifi界面時,刷新button的狀態  
  80.             }  
  81.         });  
  82.   
  83.         toggleButton.setOnClickListener(new OnClickListener() {  
  84.             @Override  
  85.             public void onClick(View v) {  
  86.                 Log.i("111", isChecked + "/" + WifiAdmin.getWifiAdmin().checkState());  
  87.                 if (isChecked) {  
  88.                     WifiAdmin.getWifiAdmin().OpenWifi();  
  89.                     frag_detail.setWifiShow();  
  90.                     // toggleButton.setText("關閉");  
  91.                     toggleButton.setChecked(false);  
  92.                     isChecked = false;  
  93.                 } else {  
  94.                     WifiAdmin.getWifiAdmin().CloseWife();  
  95.                     frag_detail.setWifiShow();  
  96.                     // toggleButton.setText("打開");  
  97.                     toggleButton.setChecked(true);  
  98.                     isChecked = true;  
  99.                 }  
  100.                 toggleButton.setClickable(false);  
  101.             }  
  102.         });  
  103.     }  
  104.   
  105.     //  
  106.     public void checktoggleButton() {  
  107.         if (WifiAdmin.getWifiAdmin().checkState() == 1) {  
  108.             toggleButton.setChecked(true);  
  109.             isChecked = true;  
  110.         }  
  111.         if (WifiAdmin.getWifiAdmin().checkState() == 3) {  
  112.             toggleButton.setChecked(false);  
  113.             isChecked = false;  
  114.         }  
  115.     }  
  116.   
  117.     public void setView() {  
  118.         wifi = (TextView) getView().findViewById(R.id.wifi);  
  119.         toggleButton = (ToggleButton) getView().findViewById(R.id.toggleButton);  
  120.         saveBut = (TextView) getView().findViewById(R.id.saveBut);  
  121.           
  122.         // 實例化右面界面,以便操縱裏面的方法F  
  123.         frag_detail = (FragementDetails) getFragmentManager().findFragmentById(R.id.frag_detail);  
  124.           
  125.         // 初始化button的裝態  
  126.         if (WifiAdmin.getWifiAdmin().checkState() == 3) {  
  127.             toggleButton.setChecked(false);  
  128.             isChecked = false;  
  129.         }  
  130.         if (WifiAdmin.getWifiAdmin().checkState() == 1) {  
  131.             toggleButton.setChecked(true);  
  132.             isChecked = true;  
  133.         }  
  134.         toggleButton.setClickable(true);  
  135.     }  
  136.   
  137.     @Override  
  138.     public void onDestroy() {  
  139.         frag_detail.stopWifiThread();  
  140.         butIsRunning = false;  
  141.         super.onDestroy();  
  142.     }  
  143.   
  144.     private void startThread() {  
  145.         butIsRunning = true;  
  146.         new Thread(new Runnable() {  
  147.   
  148.             @Override  
  149.             public void run() {  
  150.                 while (butIsRunning) {  
  151.                     //只有wifi狀態改變變化完畢之後才能允許點擊按鈕  
  152.                     if (WifiAdmin.getWifiAdmin().checkState() == 3) {  
  153.                         if (!isChecked) {  
  154.                             toggleButton.setClickable(true);  
  155.                         }  
  156.   
  157.                     } else if (WifiAdmin.getWifiAdmin().checkState() == 1) {  
  158.                         if (isChecked) {  
  159.                             toggleButton.setClickable(true);  
  160.                         }  
  161.                     }  
  162.                 }  
  163.             }  
  164.         }).start();  
  165.     }  
  166.   
  167. }  

10、右面fragment界面類

[java] view plaincopy
  1. package co.cm.fragement;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import co.cm.fragement.R;  
  6. import android.app.Fragment;  
  7. import android.net.wifi.ScanResult;  
  8. import android.net.wifi.WifiConfiguration;  
  9. import android.os.Bundle;  
  10. import android.os.Handler;  
  11. import android.os.Message;  
  12. import android.util.Log;  
  13. import android.view.LayoutInflater;  
  14. import android.view.View;  
  15. import android.view.ViewGroup;  
  16. import android.widget.BaseAdapter;  
  17. import android.widget.LinearLayout;  
  18. import android.widget.ListView;  
  19. import android.widget.RelativeLayout;  
  20. import android.widget.TextView;  
  21.   
  22. /** 
  23.  * @author yangyu 
  24.  *  功能描述:右面fragment界面類,該類實現了右面顯示的操作 
  25.  */  
  26. public class FragementDetails extends Fragment {  
  27.     private TextView mac_address, bssid, ip_address, id, info, wifiText;  
  28.       
  29.     private ListView listView;  
  30.       
  31.     private LinearLayout wifiLinear;  
  32.       
  33.     private RelativeLayout save, wifi;  
  34.       
  35.     private boolean ThreadFlag = false;  
  36.       
  37.     //wifi數據適配器  
  38.     private WifiAdapter wifiAdapter;  
  39.       
  40.     // 掃描出的網絡連接列表  
  41.     private List<ScanResult> mWifiList = new ArrayList<ScanResult>();  
  42.       
  43.     // 網絡連接列表  
  44.     private List<WifiConfiguration> mWifiConfiguration = null;  
  45.       
  46.     private int nowWifiState = 0;  
  47.   
  48.     @Override  
  49.     public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {  
  50.         return inflater.inflate(R.layout.frag_detail, container, false);  
  51.     }  
  52.   
  53.     @Override  
  54.     public void onActivityCreated(Bundle savedInstanceState) {  
  55.         super.onActivityCreated(savedInstanceState);  
  56.         setView();  
  57.         // setListener();  
  58.         setWifiShow();  
  59.   
  60.     }  
  61.   
  62.     /** 
  63.      * 顯示wifi界面 
  64.      */  
  65.     public void setWifiShow() {   
  66.         //通過隱藏顯示來達到不同頁面內容的切換  
  67.         save.setVisibility(View.GONE);  
  68.         wifi.setVisibility(View.VISIBLE);  
  69.         stopWifiThread();  
  70.         refreshWifi();  
  71.   
  72.     }  
  73.   
  74.     /** 
  75.      * 顯示保存界面 
  76.      */  
  77.     public void setSaveShow() {  
  78.         stopWifiThread();  
  79.         save.setVisibility(View.VISIBLE);  
  80.         wifi.setVisibility(View.GONE);  
  81.     }  
  82.   
  83.     /** 
  84.      * 初始化組件 
  85.      */  
  86.     public void setView() {  
  87.         // -----------------wifi-----------------  
  88.         wifiText = (TextView) getView().findViewById(R.id.wifiText);  
  89.         mac_address = (TextView) getView().findViewById(R.id.mac_address);  
  90.         bssid = (TextView) getView().findViewById(R.id.bssid);  
  91.         ip_address = (TextView) getView().findViewById(R.id.ip_address);  
  92.         id = (TextView) getView().findViewById(R.id.id);  
  93.         info = (TextView) getView().findViewById(R.id.info);  
  94.         listView = (ListView) getView().findViewById(R.id.listview);  
  95.         wifiLinear = (LinearLayout) getView().findViewById(R.id.wifiLinear);  
  96.         save = (RelativeLayout) getView().findViewById(R.id.save);  
  97.         wifi = (RelativeLayout) getView().findViewById(R.id.wifi);  
  98.         wifiAdapter = new WifiAdapter();  
  99.         listView.setAdapter(wifiAdapter);  
  100.     }  
  101.   
  102.     private Handler handler = new Handler() {  
  103.         @Override  
  104.         public void handleMessage(Message msg) {  
  105.             nowWifiState = WifiAdmin.getWifiAdmin().checkState();  
  106.             // 當wifi打開時,刷新wifi列表的內容  
  107.             if (nowWifiState == 3) {  
  108.                 mWifiList = WifiAdmin.getWifiAdmin().GetWifiList();  
  109.                 // 如果剛開始檢測的wifi列表爲空,則創建一個實例化的wifi而不是null,負責會在adpter裏面報錯  
  110.                 if (mWifiList != null) {  
  111.                     // 如果wifi列表發生改變,則更新,else不更新  
  112.                     if (!mWifiList.toString().equals(  
  113.                             WifiAdmin.getWifiAdmin().getLastWifiList().toString())) {  
  114.                         WifiAdmin.getWifiAdmin().setLastWifiList(mWifiList);  
  115.                         wifiAdapter.notifyDate();  
  116.                     }  
  117.                 } else {  
  118.                     mWifiList = new ArrayList<ScanResult>();  
  119.                 }  
  120.             }  
  121.             refreshMeathod();  
  122.   
  123.             super.handleMessage(msg);  
  124.         }  
  125.     };  
  126.   
  127.     /** 
  128.      * 刷新wifi的狀態  
  129.      */  
  130.     public void refreshWifi() {  
  131.         new Thread(new Runnable() {  
  132.             @Override  
  133.             public void run() {  
  134.                 ThreadFlag = true;  
  135.                 while (ThreadFlag) {  
  136.                     // Log.i("111", WifiAdmin.getWifiAdmin().checkState() +  
  137.                     // "!!!");  
  138.                     Message msg = handler.obtainMessage();  
  139.                     handler.sendMessage(msg);  
  140.                     try {  
  141.                         Thread.sleep(1000);  
  142.                     } catch (InterruptedException e) {  
  143.                         e.printStackTrace();  
  144.                     }  
  145.                 }  
  146.             }  
  147.         }).start();  
  148.     }  
  149.   
  150.     public void refreshMeathod() {        
  151.         // 此處可用switch  
  152.         if (nowWifiState == 3) {          
  153.             wifiLinear.setVisibility(View.VISIBLE);  
  154.             wifiText.setVisibility(View.INVISIBLE);  
  155.             mac_address.setText(WifiAdmin.getWifiAdmin().GetMacAddress() + "");  
  156.             bssid.setText(WifiAdmin.getWifiAdmin().GetBSSID() + "");  
  157.             ip_address.setText(WifiAdmin.getWifiAdmin().GetIPAddress() + "");  
  158.             id.setText(WifiAdmin.getWifiAdmin().GetNetworkId() + "");  
  159.             info.setText(WifiAdmin.getWifiAdmin().GetWifiInfo() + "");            
  160.         } else if (nowWifiState == 1) {  
  161.             wifiText.setVisibility(View.VISIBLE);  
  162.             wifiLinear.setVisibility(View.INVISIBLE);  
  163.             wifiText.setText("要查看可用的網絡,請打開wifi");  
  164.         } else if (nowWifiState == 2) {  
  165.             wifiText.setVisibility(View.VISIBLE);  
  166.             wifiLinear.setVisibility(View.INVISIBLE);  
  167.             wifiText.setText("wifi正在打開");  
  168.         } else if (nowWifiState == 4) {  
  169.             wifiText.setVisibility(View.VISIBLE);  
  170.             wifiLinear.setVisibility(View.INVISIBLE);  
  171.             wifiText.setText("wifi正在關閉");  
  172.         } else {  
  173.             wifiText.setVisibility(View.VISIBLE);  
  174.             wifiLinear.setVisibility(View.INVISIBLE);  
  175.             wifiText.setText("我不知道wifi正在做什麼");  
  176.         }  
  177.     }  
  178.   
  179.     public void stopWifiThread() {  
  180.         ThreadFlag = false;  
  181.     }  
  182.   
  183.     public class WifiAdapter extends BaseAdapter {  
  184.         @Override  
  185.         public int getCount() {           
  186.             return mWifiList.size();  
  187.         }  
  188.   
  189.         @Override  
  190.         public Object getItem(int position) {  
  191.             return mWifiList.get(position);  
  192.         }  
  193.   
  194.         @Override  
  195.         public long getItemId(int position) {  
  196.             return position;  
  197.         }  
  198.   
  199.         @Override  
  200.         public View getView(int position, View convertView, ViewGroup parent) {  
  201.             View view = convertView;  
  202.   
  203.             final ChatViewHolder vh;  
  204.   
  205.             if (convertView == null) {  
  206.                 vh = new ChatViewHolder();  
  207.                 view = View.inflate(WifiAdmin.getWifiAdmin().getmContext(),  
  208.                         R.layout.wifi_list, null);  
  209.                 vh.wifi_name = (TextView) view.findViewById(R.id.wifi_name);  
  210.   
  211.                 vh.wifi_name_state = (TextView) view  
  212.                         .findViewById(R.id.wifi_name_state);  
  213.   
  214.                 view.setTag(vh);  
  215.             } else {  
  216.                 vh = (ChatViewHolder) view.getTag();  
  217.             }  
  218.             vh.wifi_name.setText(mWifiList.get(position).SSID.toString());// 網絡的名字,唯一區別WIFI網絡的名字  
  219.             vh.wifi_name_state.setText(mWifiList.get(position).level + "");  
  220.             return view;  
  221.         }  
  222.   
  223.         public void notifyDate() {  
  224.             notifyDataSetChanged();  
  225.         }  
  226.   
  227.     }  
  228.   
  229.     public class ChatViewHolder {  
  230.         TextView wifi_name;// 網絡的名字,唯一區別WIFI網絡的名字  
  231.         TextView wifi_name_state;// 所發現的WIFI網絡信號強度  
  232.     }  
  233.   
  234. }  

11、wifiAdmin類,提供了wifi操作的方法,WifiAdmin.java:

[java] view plaincopy
  1. package co.cm.fragement;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import android.content.Context;  
  7. import android.net.wifi.ScanResult;  
  8. import android.net.wifi.WifiConfiguration;  
  9. import android.net.wifi.WifiInfo;  
  10. import android.net.wifi.WifiManager;  
  11. import android.net.wifi.WifiManager.WifiLock;  
  12. import android.util.Log;  
  13.   
  14. /** 
  15.  * @author yangyu 
  16.  *  wifiAdmin提供了wifi操作的方法 
  17.  */  
  18. public class WifiAdmin {  
  19.     private static WifiAdmin wifiAdmin;  
  20.       
  21.     private WifiManager mWifiManager = null;  
  22.       
  23.     private WifiInfo mWifiInfo = null;  
  24.       
  25.     // 掃描出的網絡連接列表  
  26.     private List<ScanResult> mWifiList = new ArrayList<ScanResult>();  
  27.       
  28.     // 掃描出的網絡連接列表  
  29.     private List<ScanResult> lastWifiList = new ArrayList<ScanResult>();  
  30.       
  31.     // 網絡連接列表  
  32.     private List<WifiConfiguration> mWifiConfiguration = null;  
  33.       
  34.     private WifiLock mWifiLock = null;  
  35.           
  36.     // 上次網絡狀態  
  37.     private int lastWifiState = 0;  
  38.   
  39.     //定義上下文Context  
  40.     Context mContext;  
  41.   
  42.     public List<ScanResult> getLastWifiList() {  
  43.         return lastWifiList;  
  44.     }  
  45.   
  46.     public void setLastWifiList(List<ScanResult> lastWifiList) {  
  47.         this.lastWifiList = lastWifiList;  
  48.     }  
  49.   
  50.     public int getLastWifiState() {  
  51.         return lastWifiState;  
  52.     }  
  53.   
  54.     public void setLastWifiState(int lastWifiState) {  
  55.         this.lastWifiState = lastWifiState;  
  56.     }  
  57.   
  58.     public static WifiAdmin getWifi() {  
  59.         return wifiAdmin;  
  60.     }  
  61.   
  62.     public Context getmContext() {  
  63.         return mContext;  
  64.     }  
  65.   
  66.     public void setmContext(Context mContext) {  
  67.         this.mContext = mContext;  
  68.     }  
  69.   
  70.     public static WifiAdmin getWifiAdmin() {  
  71.         if (wifiAdmin == null) {  
  72.             wifiAdmin = new WifiAdmin();  
  73.   
  74.         }  
  75.         return wifiAdmin;  
  76.     }  
  77.   
  78.     public void getWifiMeathod() {  
  79.         mWifiManager = (WifiManager) mContext  
  80.                 .getSystemService(mContext.WIFI_SERVICE);  
  81.         mWifiInfo = mWifiManager.getConnectionInfo();  
  82.     }  
  83.   
  84.     /** 
  85.      * 打開wifi 
  86.      */  
  87.     public void OpenWifi() {  
  88.         if (!mWifiManager.isWifiEnabled()) {  
  89.             mWifiManager.setWifiEnabled(true);  
  90.         } else {  
  91.             Log.i("111""open 失敗");  
  92.         }  
  93.     }  
  94.   
  95.     /** 
  96.      * 關閉wifi  
  97.      */  
  98.     public void CloseWife() {  
  99.         if (mWifiManager.isWifiEnabled()) {  
  100.             mWifiManager.setWifiEnabled(false);  
  101.         } else {  
  102.             Log.i("111""close 失敗");  
  103.         }  
  104.     }  
  105.   
  106.     /** 
  107.      * 鎖定wifi 
  108.      */  
  109.     public void lockWifi() {  
  110.         mWifiLock.acquire();  
  111.     }  
  112.   
  113.     public void rlockWifi() {  
  114.         if (mWifiLock.isHeld()) {  
  115.             mWifiLock.acquire();  
  116.         }  
  117.     }  
  118.   
  119.     // 檢查當前wifi狀態WIFI網卡的狀態是由一系列的整形常量來表示的。  
  120.     //1.WIFI_STATE_DISABLED : WIFI網卡不可用(1)  
  121.     //2.WIFI_STATE_DISABLING : WIFI網卡正在關閉(0)  
  122.     //3.WIFI_STATE_ENABLED : WIFI網卡可用(3)  
  123.     //4.WIFI_STATE_ENABLING : WIFI網正在打開(2) (WIFI啓動需要一段時間)  
  124.     //5.WIFI_STATE_UNKNOWN : 未知網卡狀態  
  125.     public int checkState() {  
  126.         return mWifiManager.getWifiState();  
  127.     }  
  128.   
  129.     /** 
  130.      * 創建一個wifilock 
  131.      */  
  132.     public void Createwifilock() {  
  133.         mWifiLock = mWifiManager.createWifiLock("Testss");  
  134.     }  
  135.   
  136.     /** 
  137.      * 得到配置好的網絡 
  138.      * @return 
  139.      */  
  140.     public List<WifiConfiguration> GetConfinguration() {  
  141.         return mWifiConfiguration;  
  142.     }  
  143.   
  144.     /** 
  145.      * 連接配置好的指定ID的網絡 
  146.      * @param index 
  147.      */  
  148.     public void ConnectConfiguration(int index) {  
  149.         if (index > mWifiConfiguration.size()) {  
  150.             return;  
  151.         }  
  152.         mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId,true);  
  153.     }  
  154.   
  155.     /** 
  156.      * 開始掃描網絡 
  157.      */  
  158.     public void StartScan() {  
  159.         mWifiManager.startScan();  
  160.         // 得到掃描結果  
  161.         mWifiList = mWifiManager.getScanResults();  
  162.         // 得到配置好的網絡連接  
  163.         mWifiConfiguration = mWifiManager.getConfiguredNetworks();  
  164.     }  
  165.   
  166.     /** 
  167.      * 得到網絡列表 
  168.      * @return 
  169.      */  
  170.     public List<ScanResult> GetWifiList() {  
  171.         mWifiManager.startScan();  
  172.         // 得到掃描結果  
  173.         mWifiList = mWifiManager.getScanResults();  
  174.         return mWifiList;  
  175.     }  
  176.   
  177.     public List<WifiConfiguration> getmWifiConfiguration() {  
  178.         return mWifiConfiguration;  
  179.     }  
  180.       
  181.     /** 
  182.      * 查看掃描結果 
  183.      */  
  184.     public StringBuilder LookUpScan() {  
  185.         StringBuilder stringBuilder = new StringBuilder();  
  186.         for (int i = 0; i < mWifiList.size(); i++) {  
  187.             stringBuilder.append("Index_" + new Integer(i + 1).toString() + ":");  
  188.             // 將ScanResult信息轉換成一個字符串包  
  189.             // 其中把包括:BSSID、SSID、capabilities、frequency、level  
  190.             stringBuilder.append((mWifiList.get(i)).toString());  
  191.             stringBuilder.append("\n");  
  192.         }  
  193.         return stringBuilder;  
  194.     }  
  195.       
  196.     /** 
  197.      * 得到MAC地址 
  198.      */  
  199.     public String GetMacAddress() {  
  200.         return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();  
  201.     }  
  202.       
  203.     /** 
  204.      * 得到接入點的BSSID 
  205.      */  
  206.     public String GetBSSID() {  
  207.         return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();  
  208.     }  
  209.       
  210.     /** 
  211.      * 得到IP地址 
  212.      */  
  213.     public int GetIPAddress() {  
  214.         return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();  
  215.     }  
  216.       
  217.     /** 
  218.      * 得到連接的ID 
  219.      */  
  220.     public int GetNetworkId() {  
  221.         return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();  
  222.     }  
  223.       
  224.     /** 
  225.      * 得到WifiInfo的所有信息包 
  226.      */  
  227.     public String GetWifiInfo() {  
  228.         return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();  
  229.     }  
  230.       
  231.     /** 
  232.      * 添加一個網絡並連接 
  233.      */  
  234.     public void AddNetwork(WifiConfiguration wcg) {  
  235.         int wcgID = mWifiManager.addNetwork(wcg);  
  236.         mWifiManager.enableNetwork(wcgID, true);  
  237.     }  
  238.       
  239.     /** 
  240.      * 斷開指定ID的網絡 
  241.      */  
  242.     public void DisconnectWifi(int netId) {  
  243.         mWifiManager.disableNetwork(netId);  
  244.         mWifiManager.disconnect();  
  245.     }  
  246. }  

       

           小結: 當我們需要在一個界面中處理很多事情的時候,可以推薦使用fragment,因爲他會把我們的activity分割成很多小塊,每個小塊都有他的生命週期,非常方便,而有時我們會用單例模式來存儲每個頁面都有的東西。


三、Fragment實例講解二

 

3.1 項目的效果圖                                          

                                           

 

3.2 項目結構目錄


 

3.3 代碼具體編寫


1、標題欄的佈局界面,title_view.xml:

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="50dip"  
  5.     android:background="@drawable/title_bg"  
  6.     android:orientation="horizontal" >  
  7.   
  8.     <Button  
  9.         android:id="@+id/left_btn"  
  10.         style="@style/Text.Title_Button"  
  11.         android:layout_width="wrap_content"  
  12.         android:layout_height="35dip"  
  13.         android:layout_gravity="center_vertical"  
  14.         android:background="@drawable/title_btn_back"  
  15.         android:minWidth="60dip" />  
  16.   
  17.     <TextView  
  18.         android:id="@+id/title_text"  
  19.         style="@style/Text.Title"  
  20.         android:layout_width="fill_parent"  
  21.         android:layout_height="wrap_content"  
  22.         android:layout_gravity="center_vertical"  
  23.         android:layout_weight="1" />  
  24.   
  25.     <Button  
  26.         android:id="@+id/right_btn"  
  27.         style="@style/Text.Title_Button"  
  28.         android:layout_width="wrap_content"  
  29.         android:layout_height="35dip"  
  30.         android:layout_gravity="center_vertical"  
  31.         android:background="@drawable/title_btn"  
  32.         android:minWidth="70dip" />  
  33.   
  34. </LinearLayout>  

2、首頁的fragment頁面,這裏就列出一個,fragment_home.xml:

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <com.eoe.tampletfragment.view.TitleView  
  8.         android:id="@+id/title"  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content" />  
  11.   
  12.     <TextView  
  13.         android:id="@+id/fragment_home_text"  
  14.         android:layout_width="fill_parent"  
  15.         android:layout_height="wrap_content"  
  16.         android:text="@string/fragment_home_text"  
  17.         android:textSize="18sp" />  
  18.   
  19. </LinearLayout>  

3、幫助Activity界面,activity_help.xml:

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:background="@drawable/activity_bg"  
  6.     android:orientation="vertical" >  
  7.   
  8.     <com.eoe.tampletfragment.view.TitleView  
  9.         android:id="@+id/title"  
  10.         android:layout_width="fill_parent"  
  11.         android:layout_height="wrap_content" />  
  12.   
  13. </LinearLayout>  

4、主頁面佈局,activity_main.xml:

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:background="@drawable/activity_bg"  
  6.     android:orientation="vertical" >  
  7.   
  8.     <fragment  
  9.         android:id="@+id/fragment_home"  
  10.         android:layout_width="fill_parent"  
  11.         android:layout_height="fill_parent"  
  12.         android:layout_weight="1"  
  13.         class="com.eoe.tampletfragment.fragment.HomeFragment" />  
  14.   
  15.     <fragment  
  16.         android:id="@+id/fragment_search"  
  17.         android:layout_width="fill_parent"  
  18.         android:layout_height="fill_parent"  
  19.         android:layout_weight="1"  
  20.         class="com.eoe.tampletfragment.fragment.SearchFragment" />  
  21.   
  22.     <fragment  
  23.         android:id="@+id/fragment_settings"  
  24.         android:layout_width="fill_parent"  
  25.         android:layout_height="fill_parent"  
  26.         android:layout_weight="1"  
  27.         class="com.eoe.tampletfragment.fragment.SettingsFragment" />  
  28.   
  29.     <com.eoe.tampletfragment.fragment.FragmentIndicator  
  30.         android:id="@+id/indicator"  
  31.         android:layout_width="fill_parent"  
  32.         android:layout_height="wrap_content"  
  33.         android:background="@drawable/tab_footer_bg" />  
  34.   
  35. </LinearLayout>  

 詳細說明:

  <1> 主頁面MainActivity繼承自FragmentActivity類,負責實現導航按鈕所對應頁面的顯示和隱藏。
(詳細實現見源碼)
  <2> 主頁面由底部導航欄和麪板組成。

  <3> fragment標籤所對應Fragment的實現類。
  <4> com.eoe.tampletfragment.fragment.FragmentIndicator標籤所對應的是底部導航欄。

   

5、自定義頂部工具欄,TitleView.java:

[java] view plaincopy
  1. package com.eoe.tampletfragment.view;  
  2.   
  3. import android.content.Context;  
  4. import android.util.AttributeSet;  
  5. import android.view.LayoutInflater;  
  6. import android.view.View;  
  7. import android.widget.Button;  
  8. import android.widget.FrameLayout;  
  9. import android.widget.TextView;  
  10.   
  11. import com.eoe.tampletfragment.R;  
  12.   
  13. /** 
  14.  * @author yangyu 
  15.  *  功能描述:自定義頂部工具欄 
  16.  */  
  17. public class TitleView extends FrameLayout implements View.OnClickListener {  
  18.   
  19.     private Button mLeftBtn;  
  20.     private Button mRightBtn;  
  21.     private TextView mTitle;  
  22.   
  23.     private OnLeftButtonClickListener mOnLeftButtonClickListener;  
  24.     private OnRightButtonClickListener mOnRightButtonClickListener;  
  25.   
  26.     public interface OnLeftButtonClickListener {  
  27.         public void onClick(View button);  
  28.     }  
  29.   
  30.     public interface OnRightButtonClickListener {  
  31.         public void onClick(View button);  
  32.     }  
  33.   
  34.     public void setLeftButton(String text, OnLeftButtonClickListener listener) {  
  35.         mLeftBtn.setText(text);  
  36.         mLeftBtn.setVisibility(View.VISIBLE);  
  37.         mOnLeftButtonClickListener = listener;  
  38.     }  
  39.       
  40.     public void setLeftButton(int stringID, OnLeftButtonClickListener listener) {  
  41.         mLeftBtn.setText(stringID);  
  42.         mLeftBtn.setVisibility(View.VISIBLE);  
  43.         mOnLeftButtonClickListener = listener;  
  44.     }  
  45.       
  46.     public void removeLeftButton() {  
  47.         mLeftBtn.setText("");  
  48.         mLeftBtn.setVisibility(View.INVISIBLE);  
  49.         mOnLeftButtonClickListener = null;  
  50.     }  
  51.       
  52.     public void hiddenLeftButton() {  
  53.         mLeftBtn.setVisibility(View.INVISIBLE);  
  54.     }  
  55.       
  56.     public void showLeftButton() {  
  57.         mLeftBtn.setVisibility(View.VISIBLE);  
  58.     }  
  59.       
  60.     public void setRightButton(String text, OnRightButtonClickListener listener) {  
  61.         mRightBtn.setText(text);  
  62.         mRightBtn.setVisibility(View.VISIBLE);  
  63.         mOnRightButtonClickListener = listener;  
  64.     }  
  65.       
  66.     public void setRightButton(int stringID, OnRightButtonClickListener listener) {  
  67.         mRightBtn.setText(stringID);  
  68.         mRightBtn.setVisibility(View.VISIBLE);  
  69.         mOnRightButtonClickListener = listener;  
  70.     }  
  71.       
  72.     public void removeRightButton() {  
  73.         mRightBtn.setText("");  
  74.         mRightBtn.setVisibility(View.INVISIBLE);  
  75.         mOnRightButtonClickListener = null;  
  76.     }  
  77.       
  78.     public void hiddenRightButton() {  
  79.         mRightBtn.setVisibility(View.INVISIBLE);  
  80.     }  
  81.       
  82.     public void showRightButton() {  
  83.         mRightBtn.setVisibility(View.VISIBLE);  
  84.     }  
  85.   
  86.     public TitleView(Context context) {  
  87.         this(context, null);  
  88.     }  
  89.   
  90.     public TitleView(Context context, AttributeSet attrs) {  
  91.         this(context, attrs, 0);  
  92.     }  
  93.   
  94.     public TitleView(Context context, AttributeSet attrs, int defStyle) {  
  95.         super(context, attrs, defStyle);  
  96.   
  97.         LayoutInflater inflater = (LayoutInflater) context  
  98.                 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  99.         inflater.inflate(R.layout.title_view, thistrue);  
  100.   
  101.         mLeftBtn = (Button) findViewById(R.id.left_btn);  
  102.         mLeftBtn.setVisibility(View.INVISIBLE);  
  103.         mLeftBtn.setOnClickListener(this);  
  104.         mRightBtn = (Button) findViewById(R.id.right_btn);  
  105.         mRightBtn.setVisibility(View.INVISIBLE);  
  106.         mRightBtn.setOnClickListener(this);  
  107.           
  108.         mTitle = (TextView) findViewById(R.id.title_text);  
  109.         mTitle.setVisibility(View.INVISIBLE);  
  110.     }  
  111.       
  112.     public void setTitle(String text) {  
  113.         mTitle.setVisibility(View.VISIBLE);  
  114.         mTitle.setText(text);  
  115.     }  
  116.       
  117.     public void setTitle(int stringID) {  
  118.         mTitle.setVisibility(View.VISIBLE);  
  119.         mTitle.setText(stringID);  
  120.     }  
  121.   
  122.     @Override  
  123.     public void onClick(View v) {  
  124.         switch (v.getId()) {  
  125.         case R.id.left_btn:  
  126.             if(mOnLeftButtonClickListener != null)  
  127.                 mOnLeftButtonClickListener.onClick(v);  
  128.             break;  
  129.         case R.id.right_btn:  
  130.             if(mOnRightButtonClickListener != null)  
  131.                 mOnRightButtonClickListener.onClick(v);  
  132.             break;  
  133.         }  
  134.     }  
  135.   
  136. }  

6、自定義底部工具欄,FragmentIndicator.java:

[java] view plaincopy
  1. package com.eoe.tampletfragment.fragment;  
  2.   
  3. import android.content.Context;  
  4. import android.graphics.Color;  
  5. import android.util.AttributeSet;  
  6. import android.util.TypedValue;  
  7. import android.view.Gravity;  
  8. import android.view.View;  
  9. import android.view.View.OnClickListener;  
  10. import android.widget.ImageView;  
  11. import android.widget.LinearLayout;  
  12. import android.widget.TextView;  
  13.   
  14. import com.eoe.tampletfragment.R;  
  15.   
  16. /** 
  17.  * @author yangyu 
  18.  *  功能描述:自定義底部工具欄 
  19.  */  
  20. public class FragmentIndicator extends LinearLayout implements OnClickListener {  
  21.   
  22.     private int mDefaultIndicator = 0;  
  23.   
  24.     private static int mCurIndicator;  
  25.   
  26.     private static View[] mIndicators;  
  27.   
  28.     private OnIndicateListener mOnIndicateListener;  
  29.   
  30.     private static final String TAG_ICON_0 = "icon_tag_0";  
  31.     private static final String TAG_ICON_1 = "icon_tag_1";  
  32.     private static final String TAG_ICON_2 = "icon_tag_2";  
  33.   
  34.     private static final String TAG_TEXT_0 = "text_tag_0";  
  35.     private static final String TAG_TEXT_1 = "text_tag_1";  
  36.     private static final String TAG_TEXT_2 = "text_tag_2";  
  37.       
  38.     private static final int COLOR_UNSELECT = Color.argb(1000xff0xff0xff);  
  39.     private static final int COLOR_SELECT = Color.WHITE;  
  40.   
  41.     private FragmentIndicator(Context context) {  
  42.         super(context);  
  43.     }  
  44.   
  45.     public FragmentIndicator(Context context, AttributeSet attrs) {  
  46.         super(context, attrs);  
  47.   
  48.         mCurIndicator = mDefaultIndicator;  
  49.         setOrientation(LinearLayout.HORIZONTAL);  
  50.         init();  
  51.     }  
  52.   
  53.     private View createIndicator(int iconResID, int stringResID, int stringColor,   
  54.             String iconTag, String textTag) {  
  55.         LinearLayout view = new LinearLayout(getContext());  
  56.         view.setOrientation(LinearLayout.VERTICAL);  
  57.         view.setLayoutParams(new LinearLayout.LayoutParams(  
  58.                 LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1));  
  59.         view.setGravity(Gravity.CENTER_HORIZONTAL);  
  60.   
  61.         ImageView iconView = new ImageView(getContext());  
  62.         iconView.setTag(iconTag);  
  63.         iconView.setLayoutParams(new LinearLayout.LayoutParams(  
  64.                 LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1));  
  65.         iconView.setImageResource(iconResID);  
  66.   
  67.         TextView textView = new TextView(getContext());  
  68.         textView.setTag(textTag);  
  69.         textView.setLayoutParams(new LinearLayout.LayoutParams(  
  70.                 LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1));  
  71.         textView.setTextColor(stringColor);  
  72.         textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);  
  73.         textView.setText(stringResID);  
  74.   
  75.         view.addView(iconView);  
  76.         view.addView(textView);  
  77.   
  78.         return view;  
  79.   
  80.     }  
  81.   
  82.     private void init() {  
  83.         mIndicators = new View[3];  
  84.         mIndicators[0] = createIndicator(R.drawable.ic_home_focused,  
  85.                 R.string.tab_home, COLOR_SELECT, TAG_ICON_0, TAG_TEXT_0);  
  86.         mIndicators[0].setBackgroundResource(R.drawable.indic_select);  
  87.         mIndicators[0].setTag(Integer.valueOf(0));  
  88.         mIndicators[0].setOnClickListener(this);  
  89.         addView(mIndicators[0]);  
  90.         mIndicators[1] = createIndicator(R.drawable.ic_search_normal,  
  91.                 R.string.tab_search, COLOR_UNSELECT, TAG_ICON_1, TAG_TEXT_1);  
  92.         mIndicators[1].setBackgroundColor(Color.alpha(0));  
  93.         mIndicators[1].setTag(Integer.valueOf(1));  
  94.         mIndicators[1].setOnClickListener(this);  
  95.         addView(mIndicators[1]);  
  96.         mIndicators[2] = createIndicator(R.drawable.ic_settings_normal,  
  97.                 R.string.tab_settings, COLOR_UNSELECT, TAG_ICON_2, TAG_TEXT_2);  
  98.         mIndicators[2].setBackgroundColor(Color.alpha(0));  
  99.         mIndicators[2].setTag(Integer.valueOf(2));  
  100.         mIndicators[2].setOnClickListener(this);  
  101.         addView(mIndicators[2]);  
  102.     }  
  103.   
  104.     public static void setIndicator(int which) {  
  105.         // clear previous status.  
  106.         mIndicators[mCurIndicator].setBackgroundColor(Color.alpha(0));  
  107.         ImageView prevIcon;  
  108.         TextView prevText;  
  109.         switch(mCurIndicator) {  
  110.         case 0:  
  111.             prevIcon =(ImageView) mIndicators[mCurIndicator].findViewWithTag(TAG_ICON_0);  
  112.             prevIcon.setImageResource(R.drawable.ic_home_normal);  
  113.             prevText = (TextView) mIndicators[mCurIndicator].findViewWithTag(TAG_TEXT_0);  
  114.             prevText.setTextColor(COLOR_UNSELECT);  
  115.             break;  
  116.         case 1:  
  117.             prevIcon =(ImageView) mIndicators[mCurIndicator].findViewWithTag(TAG_ICON_1);  
  118.             prevIcon.setImageResource(R.drawable.ic_search_normal);  
  119.             prevText = (TextView) mIndicators[mCurIndicator].findViewWithTag(TAG_TEXT_1);  
  120.             prevText.setTextColor(COLOR_UNSELECT);  
  121.             break;  
  122.         case 2:  
  123.             prevIcon =(ImageView) mIndicators[mCurIndicator].findViewWithTag(TAG_ICON_2);  
  124.             prevIcon.setImageResource(R.drawable.ic_settings_normal);  
  125.             prevText = (TextView) mIndicators[mCurIndicator].findViewWithTag(TAG_TEXT_2);  
  126.             prevText.setTextColor(COLOR_UNSELECT);  
  127.             break;  
  128.         }  
  129.           
  130.         // update current status.  
  131.         mIndicators[which].setBackgroundResource(R.drawable.indic_select);  
  132.         ImageView currIcon;  
  133.         TextView currText;  
  134.         switch(which) {  
  135.         case 0:  
  136.             currIcon =(ImageView) mIndicators[which].findViewWithTag(TAG_ICON_0);  
  137.             currIcon.setImageResource(R.drawable.ic_home_focused);  
  138.             currText = (TextView) mIndicators[which].findViewWithTag(TAG_TEXT_0);  
  139.             currText.setTextColor(COLOR_SELECT);  
  140.             break;  
  141.         case 1:  
  142.             currIcon =(ImageView) mIndicators[which].findViewWithTag(TAG_ICON_1);  
  143.             currIcon.setImageResource(R.drawable.ic_search_focused);  
  144.             currText = (TextView) mIndicators[which].findViewWithTag(TAG_TEXT_1);  
  145.             currText.setTextColor(COLOR_SELECT);  
  146.             break;  
  147.         case 2:  
  148.             currIcon =(ImageView) mIndicators[which].findViewWithTag(TAG_ICON_2);  
  149.             currIcon.setImageResource(R.drawable.ic_settings_focused);  
  150.             currText = (TextView) mIndicators[which].findViewWithTag(TAG_TEXT_2);  
  151.             currText.setTextColor(COLOR_SELECT);  
  152.             break;  
  153.         }  
  154.           
  155.         mCurIndicator = which;  
  156.     }  
  157.   
  158.     public interface OnIndicateListener {  
  159.         public void onIndicate(View v, int which);  
  160.     }  
  161.   
  162.     public void setOnIndicateListener(OnIndicateListener listener) {  
  163.         mOnIndicateListener = listener;  
  164.     }  
  165.   
  166.     @Override  
  167.     public void onClick(View v) {  
  168.         if (mOnIndicateListener != null) {  
  169.             int tag = (Integer) v.getTag();  
  170.             switch (tag) {  
  171.             case 0:  
  172.                 if (mCurIndicator != 0) {  
  173.                     mOnIndicateListener.onIndicate(v, 0);  
  174.                     setIndicator(0);  
  175.                 }  
  176.                 break;  
  177.             case 1:  
  178.                 if (mCurIndicator != 1) {  
  179.                     mOnIndicateListener.onIndicate(v, 1);  
  180.                     setIndicator(1);  
  181.                 }  
  182.                 break;  
  183.             case 2:  
  184.                 if (mCurIndicator != 2) {  
  185.                     mOnIndicateListener.onIndicate(v, 2);  
  186.                     setIndicator(2);  
  187.                 }  
  188.                 break;  
  189.             default:  
  190.                 break;  
  191.             }  
  192.         }  
  193.     }  
  194. }  

7、首頁fragment頁面,HomeFragment.java:

[java] view plaincopy
  1. package com.eoe.tampletfragment.fragment;  
  2.   
  3. import android.content.Intent;  
  4. import android.os.Bundle;  
  5. import android.support.v4.app.Fragment;  
  6. import android.support.v4.app.FragmentActivity;  
  7. import android.view.LayoutInflater;  
  8. import android.view.View;  
  9. import android.view.ViewGroup;  
  10. import android.widget.TextView;  
  11.   
  12. import com.eoe.tampletfragment.HelpActivity;  
  13. import com.eoe.tampletfragment.R;  
  14. import com.eoe.tampletfragment.view.TitleView;  
  15. import com.eoe.tampletfragment.view.TitleView.OnLeftButtonClickListener;  
  16. import com.eoe.tampletfragment.view.TitleView.OnRightButtonClickListener;  
  17.   
  18. /** 
  19.  * @author yangyu 
  20.  *  功能描述:首頁fragment頁面 
  21.  */  
  22. public class HomeFragment extends Fragment {  
  23.   
  24.     private View mParent;  
  25.       
  26.     private FragmentActivity mActivity;  
  27.       
  28.     private TitleView mTitle;  
  29.       
  30.     private TextView mText;  
  31.       
  32.     /** 
  33.      * Create a new instance of DetailsFragment, initialized to show the text at 
  34.      * 'index'. 
  35.      */  
  36.     public static HomeFragment newInstance(int index) {  
  37.         HomeFragment f = new HomeFragment();  
  38.   
  39.         // Supply index input as an argument.  
  40.         Bundle args = new Bundle();  
  41.         args.putInt("index", index);  
  42.         f.setArguments(args);  
  43.   
  44.         return f;  
  45.     }  
  46.   
  47.     public int getShownIndex() {  
  48.         return getArguments().getInt("index"0);  
  49.     }  
  50.   
  51.     @Override  
  52.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  53.             Bundle savedInstanceState) {  
  54.         View view = inflater.inflate(R.layout.fragment_home, container, false);  
  55.         return view;  
  56.     }  
  57.   
  58.     @Override  
  59.     public void onActivityCreated(Bundle savedInstanceState) {  
  60.         super.onActivityCreated(savedInstanceState);  
  61.         mActivity = getActivity();  
  62.         mParent = getView();  
  63.   
  64.         mTitle = (TitleView) mParent.findViewById(R.id.title);  
  65.         mTitle.setTitle(R.string.title_home);  
  66.         mTitle.setLeftButton(R.string.exit, new OnLeftButtonClickListener(){  
  67.   
  68.             @Override  
  69.             public void onClick(View button) {  
  70.                 mActivity.finish();  
  71.             }  
  72.               
  73.         });  
  74.         mTitle.setRightButton(R.string.help, new OnRightButtonClickListener() {  
  75.   
  76.             @Override  
  77.             public void onClick(View button) {  
  78.                 goHelpActivity();  
  79.             }  
  80.         });  
  81.           
  82.         mText = (TextView) mParent.findViewById(R.id.fragment_home_text);  
  83.   
  84.     }  
  85.       
  86.     private void goHelpActivity() {  
  87.         Intent intent = new Intent(mActivity, HelpActivity.class);  
  88.         startActivity(intent);  
  89.     }  
  90.   
  91.     @Override  
  92.     public void onHiddenChanged(boolean hidden) {  
  93.         super.onHiddenChanged(hidden);  
  94.     }  
  95.   
  96.     @Override  
  97.     public void onDestroy() {  
  98.         super.onDestroy();  
  99.     }  
  100.   
  101. }  

8、Activity幫助界面,HelpActivity.java:

[java] view plaincopy
  1. package com.eoe.tampletfragment;  
  2.   
  3. import android.os.Bundle;  
  4. import android.support.v4.app.FragmentActivity;  
  5. import android.view.Window;  
  6.   
  7. /** 
  8.  * @author yangyu 
  9.  *  功能描述:幫助Activity界面 
  10.  */  
  11. public class HelpActivity extends FragmentActivity {  
  12.   
  13.     @Override  
  14.     protected void onCreate(Bundle savedInstanceState) {  
  15.         super.onCreate(savedInstanceState);  
  16.         requestWindowFeature(Window.FEATURE_NO_TITLE);    
  17.         setContentView(R.layout.activity_help);  
  18.     }  
  19.   
  20. }  

9、Activity主界面,MainActivity.java:

[java] view plaincopy
  1. package com.eoe.tampletfragment;  
  2.   
  3. import android.os.Bundle;  
  4. import android.support.v4.app.Fragment;  
  5. import android.support.v4.app.FragmentActivity;  
  6. import android.view.View;  
  7. import android.view.Window;  
  8.   
  9. import com.eoe.tampletfragment.fragment.FragmentIndicator;  
  10. import com.eoe.tampletfragment.fragment.FragmentIndicator.OnIndicateListener;  
  11.   
  12. /** 
  13.  * @author yangyu 
  14.  *  功能描述:主Activity類,繼承自FragmentActivity 
  15.  */  
  16. public class MainActivity extends FragmentActivity {  
  17.   
  18.     public static Fragment[] mFragments;  
  19.   
  20.     @Override  
  21.     protected void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         requestWindowFeature(Window.FEATURE_NO_TITLE);  
  24.         setContentView(R.layout.activity_main);  
  25.   
  26.         setFragmentIndicator(0);  
  27.           
  28.     }  
  29.   
  30.     /** 
  31.      * 初始化fragment 
  32.      */  
  33.     private void setFragmentIndicator(int whichIsDefault) {  
  34.         mFragments = new Fragment[3];  
  35.         mFragments[0] = getSupportFragmentManager().findFragmentById(R.id.fragment_home);  
  36.         mFragments[1] = getSupportFragmentManager().findFragmentById(R.id.fragment_search);  
  37.         mFragments[2] = getSupportFragmentManager().findFragmentById(R.id.fragment_settings);  
  38.         getSupportFragmentManager().beginTransaction().hide(mFragments[0])  
  39.                 .hide(mFragments[1]).hide(mFragments[2]).show(mFragments[whichIsDefault]).commit();  
  40.   
  41.         FragmentIndicator mIndicator = (FragmentIndicator) findViewById(R.id.indicator);  
  42.         FragmentIndicator.setIndicator(whichIsDefault);  
  43.         mIndicator.setOnIndicateListener(new OnIndicateListener() {  
  44.             @Override  
  45.             public void onIndicate(View v, int which) {  
  46.                 getSupportFragmentManager().beginTransaction()  
  47.                         .hide(mFragments[0]).hide(mFragments[1])  
  48.                         .hide(mFragments[2]).show(mFragments[which]).commit();  
  49.             }  
  50.         });  
  51.     }  
  52.   
  53.     @Override  
  54.     protected void onResume() {  
  55.         super.onResume();  
  56.     }  
  57.       
  58.     @Override  
  59.     protected void onPause() {  
  60.         super.onPause();  
  61.     }  
  62.       
  63. }  


 

實例一項目下載地址

實例二項目下載地址








 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章