【Android UI设计与开发】第07期:底部菜单栏(二)Fragment的详细介绍和使用方法

 由于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中生成对象。

  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
  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,如下:
  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的实例,如下:
  1. FragmentManager fragmentManager = getFragmentManager();  
  2. FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();  
复制代码
一个事务是在同一时刻执行的一组动作(很像数据库中的事务)。可以用add(),remove(),replace()等方法构成事务,最后使用commit()方法提交事务。在调用commit()之前,可以用addToBackStack()把事务添加到一个后退栈中,这个后退栈属于所在的activity。有了它,就可以在用户按下返回键时,返回到fragment执行事务之前的状态。如下例:演示了如何用一个fragment代替另一个fragment,同时在后退栈中保存被代替的fragment的状态。
  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:
  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.     <TextView
  7.         android:layout_width="wrap_content"
  8.         android:layout_height="wrap_content"
  9.         android:text="无线和网络"
  10.         android:textSize="30sp" />

  11.     <TextView
  12.         android:layout_width="match_parent"
  13.         android:layout_height="1px"
  14.         android:background="@color/lineColor" />

  15.     <LinearLayout
  16.         android:layout_width="match_parent"
  17.         android:layout_height="wrap_content"
  18.         android:layout_gravity="center_vertical"
  19.         android:layout_marginLeft="10dp"
  20.         android:orientation="horizontal" >

  21.         <TextView
  22.             android:id="@+id/wifi"
  23.             android:layout_width="wrap_content"
  24.             android:layout_height="wrap_content"
  25.             android:layout_gravity="center_vertical"
  26.             android:text="WI-Fi"
  27.             android:textSize="30sp" />

  28.         <ToggleButton
  29.             android:id="@+id/toggleButton"
  30.             android:layout_width="wrap_content"
  31.             android:layout_height="wrap_content"
  32.             android:layout_gravity="center_vertical"
  33.             android:layout_marginLeft="20dp"
  34.             android:text="开" />
  35.     </LinearLayout>

  36.     <TextView
  37.         android:layout_width="match_parent"
  38.         android:layout_height="1px"
  39.         android:background="@color/lineColor" />

  40.     <TextView
  41.         android:layout_width="wrap_content"
  42.         android:layout_height="wrap_content"
  43.         android:text="设备"
  44.         android:textSize="30sp" />

  45.     <TextView
  46.         android:layout_width="match_parent"
  47.         android:layout_height="1px"
  48.         android:background="@color/lineColor" />

  49.     <TextView
  50.         android:id="@+id/saveBut"
  51.         android:layout_width="fill_parent"
  52.         android:layout_height="wrap_content"
  53.         android:layout_marginLeft="10dp"
  54.         android:text="存储"
  55.         android:textSize="35sp" />

  56. </LinearLayout>
复制代码
2、右边页面布局界面,frag_detail.xml:
  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.     <RelativeLayout
  8.         android:id="@+id/save"
  9.         android:layout_width="fill_parent"
  10.         android:layout_height="fill_parent"
  11.         android:layout_margin="10dp"
  12.         android:visibility="gone" >

  13.         <include layout="@layout/save" />
  14.     </RelativeLayout>

  15.     <RelativeLayout
  16.         android:id="@+id/wifi"
  17.         android:layout_width="fill_parent"
  18.         android:layout_height="fill_parent"
  19.         android:layout_margin="10dp"
  20.         android:visibility="gone" >

  21.         <include layout="@layout/wifi" />
  22.     </RelativeLayout>

  23. </LinearLayout></span>
复制代码
3、主布局界面,main.xml:
  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.     <fragment
  10.         android:id="@+id/frag_list"
  11.         android:name="co.cm.fragement.FragementList"
  12.         android:layout_width="fill_parent"
  13.         android:layout_height="wrap_content"
  14.         android:layout_weight="2" />

  15.     <!-- 右面页面 -->

  16.     <fragment
  17.         android:id="@+id/frag_detail"
  18.         android:name="co.cm.fragement.FragementDetails"
  19.         android:layout_width="fill_parent"
  20.         android:layout_height="wrap_content"
  21.         android:layout_weight="1" />

  22. </LinearLayout>
复制代码
4、list_item.xml:
  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.     <ImageView
  8.         android:id="@+id/img"
  9.         android:layout_width="wrap_content"
  10.         android:layout_height="wrap_content" />

  11.     <TextView
  12.         android:id="@+id/txt_title"
  13.         android:layout_width="wrap_content"
  14.         android:layout_height="wrap_content"
  15.         android:text="Large Text"
  16.         android:textAppearance="?android:attr/textAppearanceLarge" />

  17. </LinearLayout>
复制代码
5、save.xml:
  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.     <TextView
  7.         android:layout_width="match_parent"
  8.         android:layout_height="1px"
  9.         android:background="@color/lineColor" />

  10.     <TextView
  11.         android:layout_width="wrap_content"
  12.         android:layout_height="wrap_content"
  13.         android:layout_marginLeft="10dp"
  14.         android:text="内部存储空间"
  15.         android:textSize="30sp" />

  16.     <TextView
  17.         android:layout_width="wrap_content"
  18.         android:layout_height="wrap_content"
  19.         android:layout_marginBottom="5dp"
  20.         android:layout_marginLeft="10dp"
  21.         android:layout_marginTop="5dp"
  22.         android:text="1GB/1.98GB"
  23.         android:textSize="20sp" />

  24.     <TextView
  25.         android:layout_width="match_parent"
  26.         android:layout_height="1px"
  27.         android:background="@color/lineColor" />

  28.     <TextView
  29.         android:layout_width="wrap_content"
  30.         android:layout_height="wrap_content"
  31.         android:layout_marginLeft="20dp"
  32.         android:text="总容量"
  33.         android:textSize="30sp" />

  34.     <TextView
  35.         android:layout_width="wrap_content"
  36.         android:layout_height="wrap_content"
  37.         android:layout_marginBottom="5dp"
  38.         android:layout_marginLeft="20dp"
  39.         android:layout_marginTop="5dp"
  40.         android:text="1.98GB"
  41.         android:textSize="20sp" />

  42.     <TextView
  43.         android:layout_width="match_parent"
  44.         android:layout_height="1px"
  45.         android:background="@color/lineColor" />

  46. </LinearLayout>
复制代码
6、wifi_list:
  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.     <TextView
  7.         android:id="@+id/wifi_name"
  8.         android:layout_width="match_parent"
  9.         android:layout_height="wrap_content"
  10.         android:text="qinjin_tp_2" />

  11.     <LinearLayout
  12.         android:layout_width="match_parent"
  13.         android:layout_height="wrap_content"
  14.         android:orientation="horizontal" >

  15.         <TextView
  16.             android:layout_width="wrap_content"
  17.             android:layout_height="wrap_content"
  18.             android:text="信号强度  :" />

  19.         <TextView
  20.             android:id="@+id/wifi_name_state"
  21.             android:layout_width="match_parent"
  22.             android:layout_height="wrap_content"
  23.             android:text="还没有连接" />
  24.     </LinearLayout>

  25. </LinearLayout>
复制代码
7、wifi.xml:
  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.     <LinearLayout
  7.         android:id="@+id/wifiLinear"
  8.         android:layout_width="match_parent"
  9.         android:layout_height="wrap_content"
  10.         android:orientation="vertical" >

  11.         <LinearLayout
  12.             android:layout_width="match_parent"
  13.             android:layout_height="wrap_content"
  14.             android:orientation="vertical" >

  15.             <TextView
  16.                 android:layout_width="wrap_content"
  17.                 android:layout_height="wrap_content"
  18.                 android:text="MAC地址  :"
  19.                 android:textSize="@dimen/textsize" />

  20.             <TextView
  21.                 android:id="@+id/mac_address"
  22.                 android:layout_width="wrap_content"
  23.                 android:layout_height="wrap_content"
  24.                 android:text="MAC地址 "
  25.                 android:textSize="@dimen/textsize" />
  26.         </LinearLayout>

  27.         <LinearLayout
  28.             android:layout_width="match_parent"
  29.             android:layout_height="wrap_content"
  30.             android:orientation="vertical" >

  31.             <TextView
  32.                 android:layout_width="wrap_content"
  33.                 android:layout_height="wrap_content"
  34.                 android:text="接入点的BSSID :"
  35.                 android:textSize="@dimen/textsize" />

  36.             <TextView
  37.                 android:id="@+id/bssid"
  38.                 android:layout_width="wrap_content"
  39.                 android:layout_height="wrap_content"
  40.                 android:text="接入点的BSSID "
  41.                 android:textSize="@dimen/textsize" />
  42.         </LinearLayout>

  43.         <LinearLayout
  44.             android:layout_width="match_parent"
  45.             android:layout_height="wrap_content"
  46.             android:orientation="vertical" >

  47.             <TextView
  48.                 android:layout_width="wrap_content"
  49.                 android:layout_height="wrap_content"
  50.                 android:text="IP地址: "
  51.                 android:textSize="@dimen/textsize" />

  52.             <TextView
  53.                 android:id="@+id/ip_address"
  54.                 android:layout_width="wrap_content"
  55.                 android:layout_height="wrap_content"
  56.                 android:text="IP地址 "
  57.                 android:textSize="@dimen/textsize" />
  58.         </LinearLayout>

  59.         <LinearLayout
  60.             android:layout_width="match_parent"
  61.             android:layout_height="wrap_content"
  62.             android:orientation="vertical" >

  63.             <TextView
  64.                 android:layout_width="wrap_content"
  65.                 android:layout_height="wrap_content"
  66.                 android:text="id  "
  67.                 android:textSize="@dimen/textsize" />

  68.             <TextView
  69.                 android:id="@+id/id"
  70.                 android:layout_width="wrap_content"
  71.                 android:layout_height="wrap_content"
  72.                 android:text="id "
  73.                 android:textSize="@dimen/textsize" />
  74.         </LinearLayout>

  75.         <LinearLayout
  76.             android:layout_width="match_parent"
  77.             android:layout_height="wrap_content"
  78.             android:orientation="vertical" >

  79.             <TextView
  80.                 android:layout_width="wrap_content"
  81.                 android:layout_height="wrap_content"
  82.                 android:text=" WifiInfo的所有信息包   "
  83.                 android:textSize="@dimen/textsize" />

  84.             <TextView
  85.                 android:id="@+id/info"
  86.                 android:layout_width="wrap_content"
  87.                 android:layout_height="wrap_content"
  88.                 android:text="WifiInfo的所有信息包  "
  89.                 android:textSize="@dimen/textsize" />
  90.         </LinearLayout>

  91.         <ListView
  92.             android:id="@+id/listview"
  93.             android:layout_width="fill_parent"
  94.             android:layout_height="fill_parent"
  95.             android:layout_marginBottom="2dp" >
  96.         </ListView>
  97.     </LinearLayout>

  98.     <TextView
  99.         android:id="@+id/wifiText"
  100.         android:layout_width="wrap_content"
  101.         android:layout_height="wrap_content"
  102.         android:layout_centerInParent="true"
  103.         android:text="要查看可用的网络,请打开wifi"
  104.         android:textSize="@dimen/textsize" />

  105. </RelativeLayout>
复制代码
8、主界面类,AndroidFragmentActivity.java:
  1. package co.cm.fragement;

  2. import co.cm.fragement.R;
  3. import android.app.Activity;
  4. import android.content.Context;
  5. import android.os.Bundle;

  6. public class AndroidFragmentActivity extends Activity {
  7.         // 主activity
  8.         @Override
  9.         public void onCreate(Bundle savedInstanceState) {
  10.                 super.onCreate(savedInstanceState);
  11.                 setContentView(R.layout.main);
  12.                 WifiAdmin.getWifiAdmin().setmContext(AndroidFragmentActivity.this);
  13.                 WifiAdmin.getWifiAdmin().getWifiMeathod();
  14.         }
  15. }
复制代码
9、左面fragment界面类,FragmentList.java:
  1. package co.cm.fragement;

  2. import co.cm.fragement.R;

  3. import android.app.Fragment;
  4. import android.os.Bundle;
  5. import android.os.Handler;
  6. import android.os.Message;
  7. import android.util.Log;
  8. import android.view.LayoutInflater;
  9. import android.view.View;
  10. import android.view.View.OnClickListener;
  11. import android.view.ViewGroup;
  12. import android.widget.CompoundButton;
  13. import android.widget.CompoundButton.OnCheckedChangeListener;
  14. import android.widget.LinearLayout;
  15. import android.widget.TextView;
  16. import android.widget.ToggleButton;

  17. /**
  18. * @author yuyang
  19. *        功能描述:左面fragment界面类,该类提供了选项操作
  20. */
  21. public class FragementList extends Fragment {
  22.         //点击切换到wifi存储界面
  23.         private TextView wifi;
  24.         
  25.         //点击切换到save存储界面
  26.         private TextView saveBut;
  27.         
  28.         //定义右面fragment实例
  29.         private FragementDetails frag_detail;
  30.         
  31.         //打开关闭wifi按钮
  32.         private ToggleButton toggleButton;
  33.                 
  34.         //toggleButton按钮是否被点击
  35.         private boolean isChecked = false;
  36.         
  37.         //监听button状态线程标志位
  38.         private boolean butIsRunning = false;

  39.         @Override
  40.         public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
  41.                 // 在这里初始化fragment的页面
  42.                 return inflater.inflate(R.layout.frag_list, container, false);
  43.         }

  44.         @Override
  45.         public void onActivityCreated(Bundle savedInstanceState) {
  46.                 super.onActivityCreated(savedInstanceState);
  47.                 // 由于fragment不是activity,不是oncreated,而是onActivityCreated
  48.                 setView();
  49.                 setListener();

  50.                 startThread();// 启动控制button的线程,当wifi状态不是在1或者3的时候,不可点击,
  51.                 // if (frag != null && frag.isInLayout()) {
  52.                 // switch (arg2) {
  53.                 // case 0:
  54.                 // frag.setText("0000");
  55.         }

  56.         /**
  57.          * 给按钮设置监听
  58.          */
  59.         public void setListener() {        
  60.                 saveBut.setOnClickListener(new OnClickListener() {
  61.                         @Override
  62.                         public void onClick(View v) {
  63.                                 frag_detail.setSaveShow();
  64.                         }
  65.                 });
  66.                 
  67.                 wifi.setOnClickListener(new OnClickListener() {
  68.                         @Override
  69.                         public void onClick(View v) {
  70.                                 frag_detail.setWifiShow();
  71.                                 Log.i("111", WifiAdmin.getWifiAdmin().checkState() + "===-=-");
  72.                                 checktoggleButton();// 当点回到wifi界面时,刷新button的状态
  73.                         }
  74.                 });

  75.                 toggleButton.setOnClickListener(new OnClickListener() {
  76.                         @Override
  77.                         public void onClick(View v) {
  78.                                 Log.i("111", isChecked + "/" + WifiAdmin.getWifiAdmin().checkState());
  79.                                 if (isChecked) {
  80.                                         WifiAdmin.getWifiAdmin().OpenWifi();
  81.                                         frag_detail.setWifiShow();
  82.                                         // toggleButton.setText("关闭");
  83.                                         toggleButton.setChecked(false);
  84.                                         isChecked = false;
  85.                                 } else {
  86.                                         WifiAdmin.getWifiAdmin().CloseWife();
  87.                                         frag_detail.setWifiShow();
  88.                                         // toggleButton.setText("打开");
  89.                                         toggleButton.setChecked(true);
  90.                                         isChecked = true;
  91.                                 }
  92.                                 toggleButton.setClickable(false);
  93.                         }
  94.                 });
  95.         }

  96.         //
  97.         public void checktoggleButton() {
  98.                 if (WifiAdmin.getWifiAdmin().checkState() == 1) {
  99.                         toggleButton.setChecked(true);
  100.                         isChecked = true;
  101.                 }
  102.                 if (WifiAdmin.getWifiAdmin().checkState() == 3) {
  103.                         toggleButton.setChecked(false);
  104.                         isChecked = false;
  105.                 }
  106.         }

  107.         public void setView() {
  108.                 wifi = (TextView) getView().findViewById(R.id.wifi);
  109.                 toggleButton = (ToggleButton) getView().findViewById(R.id.toggleButton);
  110.                 saveBut = (TextView) getView().findViewById(R.id.saveBut);
  111.                 
  112.                 // 实例化右面界面,以便操纵里面的方法F
  113.                 frag_detail = (FragementDetails) getFragmentManager().findFragmentById(R.id.frag_detail);
  114.                 
  115.                 // 初始化button的装态
  116.                 if (WifiAdmin.getWifiAdmin().checkState() == 3) {
  117.                         toggleButton.setChecked(false);
  118.                         isChecked = false;
  119.                 }
  120.                 if (WifiAdmin.getWifiAdmin().checkState() == 1) {
  121.                         toggleButton.setChecked(true);
  122.                         isChecked = true;
  123.                 }
  124.                 toggleButton.setClickable(true);
  125.         }

  126.         @Override
  127.         public void onDestroy() {
  128.                 frag_detail.stopWifiThread();
  129.                 butIsRunning = false;
  130.                 super.onDestroy();
  131.         }

  132.         private void startThread() {
  133.                 butIsRunning = true;
  134.                 new Thread(new Runnable() {

  135.                         @Override
  136.                         public void run() {
  137.                                 while (butIsRunning) {
  138.                                         //只有wifi状态改变变化完毕之后才能允许点击按钮
  139.                                         if (WifiAdmin.getWifiAdmin().checkState() == 3) {
  140.                                                 if (!isChecked) {
  141.                                                         toggleButton.setClickable(true);
  142.                                                 }

  143.                                         } else if (WifiAdmin.getWifiAdmin().checkState() == 1) {
  144.                                                 if (isChecked) {
  145.                                                         toggleButton.setClickable(true);
  146.                                                 }
  147.                                         }
  148.                                 }
  149.                         }
  150.                 }).start();
  151.         }

  152. }
复制代码
10、右面fragment界面类
  1. package co.cm.fragement;

  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import co.cm.fragement.R;
  5. import android.app.Fragment;
  6. import android.net.wifi.ScanResult;
  7. import android.net.wifi.WifiConfiguration;
  8. import android.os.Bundle;
  9. import android.os.Handler;
  10. import android.os.Message;
  11. import android.util.Log;
  12. import android.view.LayoutInflater;
  13. import android.view.View;
  14. import android.view.ViewGroup;
  15. import android.widget.BaseAdapter;
  16. import android.widget.LinearLayout;
  17. import android.widget.ListView;
  18. import android.widget.RelativeLayout;
  19. import android.widget.TextView;

  20. /**
  21. * @author yangyu
  22. *        功能描述:右面fragment界面类,该类实现了右面显示的操作
  23. */
  24. public class FragementDetails extends Fragment {
  25.         private TextView mac_address, bssid, ip_address, id, info, wifiText;
  26.         
  27.         private ListView listView;
  28.         
  29.         private LinearLayout wifiLinear;
  30.         
  31.         private RelativeLayout save, wifi;
  32.         
  33.         private boolean ThreadFlag = false;
  34.         
  35.         //wifi数据适配器
  36.         private WifiAdapter wifiAdapter;
  37.         
  38.         // 扫描出的网络连接列表
  39.         private List<ScanResult> mWifiList = new ArrayList<ScanResult>();
  40.         
  41.         // 网络连接列表
  42.         private List<WifiConfiguration> mWifiConfiguration = null;
  43.         
  44.         private int nowWifiState = 0;

  45.         @Override
  46.         public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
  47.                 return inflater.inflate(R.layout.frag_detail, container, false);
  48.         }

  49.         @Override
  50.         public void onActivityCreated(Bundle savedInstanceState) {
  51.                 super.onActivityCreated(savedInstanceState);
  52.                 setView();
  53.                 // setListener();
  54.                 setWifiShow();

  55.         }

  56.         /**
  57.          * 显示wifi界面
  58.          */
  59.         public void setWifiShow() {        
  60.                 //通过隐藏显示来达到不同页面内容的切换
  61.                 save.setVisibility(View.GONE);
  62.                 wifi.setVisibility(View.VISIBLE);
  63.                 stopWifiThread();
  64.                 refreshWifi();

  65.         }

  66.         /**
  67.          * 显示保存界面
  68.          */
  69.         public void setSaveShow() {
  70.                 stopWifiThread();
  71.                 save.setVisibility(View.VISIBLE);
  72.                 wifi.setVisibility(View.GONE);
  73.         }

  74.         /**
  75.          * 初始化组件
  76.          */
  77.         public void setView() {
  78.                 // -----------------wifi-----------------
  79.                 wifiText = (TextView) getView().findViewById(R.id.wifiText);
  80.                 mac_address = (TextView) getView().findViewById(R.id.mac_address);
  81.                 bssid = (TextView) getView().findViewById(R.id.bssid);
  82.                 ip_address = (TextView) getView().findViewById(R.id.ip_address);
  83.                 id = (TextView) getView().findViewById(R.id.id);
  84.                 info = (TextView) getView().findViewById(R.id.info);
  85.                 listView = (ListView) getView().findViewById(R.id.listview);
  86.                 wifiLinear = (LinearLayout) getView().findViewById(R.id.wifiLinear);
  87.                 save = (RelativeLayout) getView().findViewById(R.id.save);
  88.                 wifi = (RelativeLayout) getView().findViewById(R.id.wifi);
  89.                 wifiAdapter = new WifiAdapter();
  90.                 listView.setAdapter(wifiAdapter);
  91.         }

  92.         private Handler handler = new Handler() {
  93.                 @Override
  94.                 public void handleMessage(Message msg) {
  95.                         nowWifiState = WifiAdmin.getWifiAdmin().checkState();
  96.                         // 当wifi打开时,刷新wifi列表的内容
  97.                         if (nowWifiState == 3) {
  98.                                 mWifiList = WifiAdmin.getWifiAdmin().GetWifiList();
  99.                                 // 如果刚开始检测的wifi列表为空,则创建一个实例化的wifi而不是null,负责会在adpter里面报错
  100.                                 if (mWifiList != null) {
  101.                                         // 如果wifi列表发生改变,则更新,else不更新
  102.                                         if (!mWifiList.toString().equals(
  103.                                                         WifiAdmin.getWifiAdmin().getLastWifiList().toString())) {
  104.                                                 WifiAdmin.getWifiAdmin().setLastWifiList(mWifiList);
  105.                                                 wifiAdapter.notifyDate();
  106.                                         }
  107.                                 } else {
  108.                                         mWifiList = new ArrayList<ScanResult>();
  109.                                 }
  110.                         }
  111.                         refreshMeathod();

  112.                         super.handleMessage(msg);
  113.                 }
  114.         };

  115.         /**
  116.          * 刷新wifi的状态 
  117.          */
  118.         public void refreshWifi() {
  119.                 new Thread(new Runnable() {
  120.                         @Override
  121.                         public void run() {
  122.                                 ThreadFlag = true;
  123.                                 while (ThreadFlag) {
  124.                                         // Log.i("111", WifiAdmin.getWifiAdmin().checkState() +
  125.                                         // "!!!");
  126.                                         Message msg = handler.obtainMessage();
  127.                                         handler.sendMessage(msg);
  128.                                         try {
  129.                                                 Thread.sleep(1000);
  130.                                         } catch (InterruptedException e) {
  131.                                                 e.printStackTrace();
  132.                                         }
  133.                                 }
  134.                         }
  135.                 }).start();
  136.         }

  137.         public void refreshMeathod() {                
  138.                 // 此处可用switch
  139.                 if (nowWifiState == 3) {                
  140.                         wifiLinear.setVisibility(View.VISIBLE);
  141.                         wifiText.setVisibility(View.INVISIBLE);
  142.                         mac_address.setText(WifiAdmin.getWifiAdmin().GetMacAddress() + "");
  143.                         bssid.setText(WifiAdmin.getWifiAdmin().GetBSSID() + "");
  144.                         ip_address.setText(WifiAdmin.getWifiAdmin().GetIPAddress() + "");
  145.                         id.setText(WifiAdmin.getWifiAdmin().GetNetworkId() + "");
  146.                         info.setText(WifiAdmin.getWifiAdmin().GetWifiInfo() + "");                        
  147.                 } else if (nowWifiState == 1) {
  148.                         wifiText.setVisibility(View.VISIBLE);
  149.                         wifiLinear.setVisibility(View.INVISIBLE);
  150.                         wifiText.setText("要查看可用的网络,请打开wifi");
  151.                 } else if (nowWifiState == 2) {
  152.                         wifiText.setVisibility(View.VISIBLE);
  153.                         wifiLinear.setVisibility(View.INVISIBLE);
  154.                         wifiText.setText("wifi正在打开");
  155.                 } else if (nowWifiState == 4) {
  156.                         wifiText.setVisibility(View.VISIBLE);
  157.                         wifiLinear.setVisibility(View.INVISIBLE);
  158.                         wifiText.setText("wifi正在关闭");
  159.                 } else {
  160.                         wifiText.setVisibility(View.VISIBLE);
  161.                         wifiLinear.setVisibility(View.INVISIBLE);
  162.                         wifiText.setText("我不知道wifi正在做什么");
  163.                 }
  164.         }

  165.         public void stopWifiThread() {
  166.                 ThreadFlag = false;
  167.         }

  168.         public class WifiAdapter extends BaseAdapter {
  169.                 @Override
  170.                 public int getCount() {                        
  171.                         return mWifiList.size();
  172.                 }

  173.                 @Override
  174.                 public Object getItem(int position) {
  175.                         return mWifiList.get(position);
  176.                 }

  177.                 @Override
  178.                 public long getItemId(int position) {
  179.                         return position;
  180.                 }

  181.                 @Override
  182.                 public View getView(int position, View convertView, ViewGroup parent) {
  183.                         View view = convertView;

  184.                         final ChatViewHolder vh;

  185.                         if (convertView == null) {
  186.                                 vh = new ChatViewHolder();
  187.                                 view = View.inflate(WifiAdmin.getWifiAdmin().getmContext(),
  188.                                                 R.layout.wifi_list, null);
  189.                                 vh.wifi_name = (TextView) view.findViewById(R.id.wifi_name);

  190.                                 vh.wifi_name_state = (TextView) view
  191.                                                 .findViewById(R.id.wifi_name_state);

  192.                                 view.setTag(vh);
  193.                         } else {
  194.                                 vh = (ChatViewHolder) view.getTag();
  195.                         }
  196.                         vh.wifi_name.setText(mWifiList.get(position).SSID.toString());// 网络的名字,唯一区别WIFI网络的名字
  197.                         vh.wifi_name_state.setText(mWifiList.get(position).level + "");
  198.                         return view;
  199.                 }

  200.                 public void notifyDate() {
  201.                         notifyDataSetChanged();
  202.                 }

  203.         }

  204.         public class ChatViewHolder {
  205.                 TextView wifi_name;// 网络的名字,唯一区别WIFI网络的名字
  206.                 TextView wifi_name_state;// 所发现的WIFI网络信号强度
  207.         }

  208. }
复制代码
11、wifiAdmin类,提供了wifi操作的方法,WifiAdmin.java:
  1. package co.cm.fragement;

  2. import java.util.ArrayList;
  3. import java.util.List;

  4. import android.content.Context;
  5. import android.net.wifi.ScanResult;
  6. import android.net.wifi.WifiConfiguration;
  7. import android.net.wifi.WifiInfo;
  8. import android.net.wifi.WifiManager;
  9. import android.net.wifi.WifiManager.WifiLock;
  10. import android.util.Log;

  11. /**
  12. * @author yangyu
  13. *        wifiAdmin提供了wifi操作的方法
  14. */
  15. public class WifiAdmin {
  16.         private static WifiAdmin wifiAdmin;
  17.         
  18.         private WifiManager mWifiManager = null;
  19.         
  20.         private WifiInfo mWifiInfo = null;
  21.         
  22.         // 扫描出的网络连接列表
  23.         private List<ScanResult> mWifiList = new ArrayList<ScanResult>();
  24.         
  25.         // 扫描出的网络连接列表
  26.         private List<ScanResult> lastWifiList = new ArrayList<ScanResult>();
  27.         
  28.         // 网络连接列表
  29.         private List<WifiConfiguration> mWifiConfiguration = null;
  30.         
  31.         private WifiLock mWifiLock = null;
  32.                 
  33.         // 上次网络状态
  34.         private int lastWifiState = 0;

  35.         //定义上下文Context
  36.         Context mContext;

  37.         public List<ScanResult> getLastWifiList() {
  38.                 return lastWifiList;
  39.         }

  40.         public void setLastWifiList(List<ScanResult> lastWifiList) {
  41.                 this.lastWifiList = lastWifiList;
  42.         }

  43.         public int getLastWifiState() {
  44.                 return lastWifiState;
  45.         }

  46.         public void setLastWifiState(int lastWifiState) {
  47.                 this.lastWifiState = lastWifiState;
  48.         }

  49.         public static WifiAdmin getWifi() {
  50.                 return wifiAdmin;
  51.         }

  52.         public Context getmContext() {
  53.                 return mContext;
  54.         }

  55.         public void setmContext(Context mContext) {
  56.                 this.mContext = mContext;
  57.         }

  58.         public static WifiAdmin getWifiAdmin() {
  59.                 if (wifiAdmin == null) {
  60.                         wifiAdmin = new WifiAdmin();

  61.                 }
  62.                 return wifiAdmin;
  63.         }

  64.         public void getWifiMeathod() {
  65.                 mWifiManager = (WifiManager) mContext
  66.                                 .getSystemService(mContext.WIFI_SERVICE);
  67.                 mWifiInfo = mWifiManager.getConnectionInfo();
  68.         }

  69.         /**
  70.          * 打开wifi
  71.          */
  72.         public void OpenWifi() {
  73.                 if (!mWifiManager.isWifiEnabled()) {
  74.                         mWifiManager.setWifiEnabled(true);
  75.                 } else {
  76.                         Log.i("111", "open 失败");
  77.                 }
  78.         }

  79.         /**
  80.          * 关闭wifi 
  81.          */
  82.         public void CloseWife() {
  83.                 if (mWifiManager.isWifiEnabled()) {
  84.                         mWifiManager.setWifiEnabled(false);
  85.                 } else {
  86.                         Log.i("111", "close 失败");
  87.                 }
  88.         }

  89.         /**
  90.          * 锁定wifi
  91.          */
  92.         public void lockWifi() {
  93.                 mWifiLock.acquire();
  94.         }

  95.         public void rlockWifi() {
  96.                 if (mWifiLock.isHeld()) {
  97.                         mWifiLock.acquire();
  98.                 }
  99.         }

  100.         // 检查当前wifi状态WIFI网卡的状态是由一系列的整形常量来表示的。
  101.         //1.WIFI_STATE_DISABLED : WIFI网卡不可用(1)
  102.         //2.WIFI_STATE_DISABLING : WIFI网卡正在关闭(0)
  103.         //3.WIFI_STATE_ENABLED : WIFI网卡可用(3)
  104.         //4.WIFI_STATE_ENABLING : WIFI网正在打开(2) (WIFI启动需要一段时间)
  105.         //5.WIFI_STATE_UNKNOWN : 未知网卡状态
  106.         public int checkState() {
  107.                 return mWifiManager.getWifiState();
  108.         }

  109.         /**
  110.          * 创建一个wifilock
  111.          */
  112.         public void Createwifilock() {
  113.                 mWifiLock = mWifiManager.createWifiLock("Testss");
  114.         }

  115.         /**
  116.          * 得到配置好的网络
  117.          * @return
  118.          */
  119.         public List<WifiConfiguration> GetConfinguration() {
  120.                 return mWifiConfiguration;
  121.         }

  122.         /**
  123.          * 连接配置好的指定ID的网络
  124.          * @param index
  125.          */
  126.         public void ConnectConfiguration(int index) {
  127.                 if (index > mWifiConfiguration.size()) {
  128.                         return;
  129.                 }
  130.                 mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId,true);
  131.         }

  132.         /**
  133.          * 开始扫描网络
  134.          */
  135.         public void StartScan() {
  136.                 mWifiManager.startScan();
  137.                 // 得到扫描结果
  138.                 mWifiList = mWifiManager.getScanResults();
  139.                 // 得到配置好的网络连接
  140.                 mWifiConfiguration = mWifiManager.getConfiguredNetworks();
  141.         }

  142.         /**
  143.          * 得到网络列表
  144.          * @return
  145.          */
  146.         public List<ScanResult> GetWifiList() {
  147.                 mWifiManager.startScan();
  148.                 // 得到扫描结果
  149.                 mWifiList = mWifiManager.getScanResults();
  150.                 return mWifiList;
  151.         }

  152.         public List<WifiConfiguration> getmWifiConfiguration() {
  153.                 return mWifiConfiguration;
  154.         }
  155.         
  156.         /**
  157.          * 查看扫描结果
  158.          */
  159.         public StringBuilder LookUpScan() {
  160.                 StringBuilder stringBuilder = new StringBuilder();
  161.                 for (int i = 0; i < mWifiList.size(); i++) {
  162.                         stringBuilder.append("Index_" + new Integer(i + 1).toString() + ":");
  163.                         // 将ScanResult信息转换成一个字符串包
  164.                         // 其中把包括:BSSID、SSID、capabilities、frequency、level
  165.                         stringBuilder.append((mWifiList.get(i)).toString());
  166.                         stringBuilder.append("\n");
  167.                 }
  168.                 return stringBuilder;
  169.         }
  170.         
  171.         /**
  172.          * 得到MAC地址
  173.          */
  174.         public String GetMacAddress() {
  175.                 return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
  176.         }
  177.         
  178.         /**
  179.          * 得到接入点的BSSID
  180.          */
  181.         public String GetBSSID() {
  182.                 return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
  183.         }
  184.         
  185.         /**
  186.          * 得到IP地址
  187.          */
  188.         public int GetIPAddress() {
  189.                 return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
  190.         }
  191.         
  192.         /**
  193.          * 得到连接的ID
  194.          */
  195.         public int GetNetworkId() {
  196.                 return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
  197.         }
  198.         
  199.         /**
  200.          * 得到WifiInfo的所有信息包
  201.          */
  202.         public String GetWifiInfo() {
  203.                 return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
  204.         }
  205.         
  206.         /**
  207.          * 添加一个网络并连接
  208.          */
  209.         public void AddNetwork(WifiConfiguration wcg) {
  210.                 int wcgID = mWifiManager.addNetwork(wcg);
  211.                 mWifiManager.enableNetwork(wcgID, true);
  212.         }
  213.         
  214.         /**
  215.          * 断开指定ID的网络
  216.          */
  217.         public void DisconnectWifi(int netId) {
  218.                 mWifiManager.disableNetwork(netId);
  219.                 mWifiManager.disconnect();
  220.         }
  221. }
复制代码
小结: 当我们需要在一个界面中处理很多事情的时候,可以推荐使用fragment,因为他会把我们的activity分割成很多小块,每个小块都有他的生命周期,非常方便,而有时我们会用单例模式来存储每个页面都有的东西。
三、Fragment实例讲解二 3.1 项目的效果图                                           3.2 项目结构目录
3.3 代码具体编写1、标题栏的布局界面,title_view.xml:
  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.     <Button
  8.         android:id="@+id/left_btn"
  9.         style="@style/Text.Title_Button"
  10.         android:layout_width="wrap_content"
  11.         android:layout_height="35dip"
  12.         android:layout_gravity="center_vertical"
  13.         android:background="@drawable/title_btn_back"
  14.         android:minWidth="60dip" />

  15.     <TextView
  16.         android:id="@+id/title_text"
  17.         style="@style/Text.Title"
  18.         android:layout_width="fill_parent"
  19.         android:layout_height="wrap_content"
  20.         android:layout_gravity="center_vertical"
  21.         android:layout_weight="1" />

  22.     <Button
  23.         android:id="@+id/right_btn"
  24.         style="@style/Text.Title_Button"
  25.         android:layout_width="wrap_content"
  26.         android:layout_height="35dip"
  27.         android:layout_gravity="center_vertical"
  28.         android:background="@drawable/title_btn"
  29.         android:minWidth="70dip" />

  30. </LinearLayout>
复制代码
2、首页的fragment页面,这里就列出一个,fragment_home.xml:
  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.     <com.eoe.tampletfragment.view.TitleView
  7.         android:id="@+id/title"
  8.         android:layout_width="fill_parent"
  9.         android:layout_height="wrap_content" />

  10.     <TextView
  11.         android:id="@+id/fragment_home_text"
  12.         android:layout_width="fill_parent"
  13.         android:layout_height="wrap_content"
  14.         android:text="@string/fragment_home_text"
  15.         android:textSize="18sp" />

  16. </LinearLayout>
复制代码
2、首页的fragment页面,这里就列出一个,fragment_home.xml:
  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.     <com.eoe.tampletfragment.view.TitleView
  7.         android:id="@+id/title"
  8.         android:layout_width="fill_parent"
  9.         android:layout_height="wrap_content" />

  10.     <TextView
  11.         android:id="@+id/fragment_home_text"
  12.         android:layout_width="fill_parent"
  13.         android:layout_height="wrap_content"
  14.         android:text="@string/fragment_home_text"
  15.         android:textSize="18sp" />

  16. </LinearLayout>
复制代码
3、帮助Activity界面,activity_help.xml:
  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.     <com.eoe.tampletfragment.view.TitleView
  8.         android:id="@+id/title"
  9.         android:layout_width="fill_parent"
  10.         android:layout_height="wrap_content" />

  11. </LinearLayout>
复制代码
4、主页面布局,activity_main.xml:
  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.     <fragment
  8.         android:id="@+id/fragment_home"
  9.         android:layout_width="fill_parent"
  10.         android:layout_height="fill_parent"
  11.         android:layout_weight="1"
  12.         class="com.eoe.tampletfragment.fragment.HomeFragment" />

  13.     <fragment
  14.         android:id="@+id/fragment_search"
  15.         android:layout_width="fill_parent"
  16.         android:layout_height="fill_parent"
  17.         android:layout_weight="1"
  18.         class="com.eoe.tampletfragment.fragment.SearchFragment" />

  19.     <fragment
  20.         android:id="@+id/fragment_settings"
  21.         android:layout_width="fill_parent"
  22.         android:layout_height="fill_parent"
  23.         android:layout_weight="1"
  24.         class="com.eoe.tampletfragment.fragment.SettingsFragment" />

  25.     <com.eoe.tampletfragment.fragment.FragmentIndicator
  26.         android:id="@+id/indicator"
  27.         android:layout_width="fill_parent"
  28.         android:layout_height="wrap_content"
  29.         android:background="@drawable/tab_footer_bg" />

  30. </LinearLayout>
复制代码
详细说明:  <1> 主页面MainActivity继承自FragmentActivity类,负责实现导航按钮所对应页面的显示和隐藏。
(详细实现见源码)
  <2> 主页面由底部导航栏和面板组成。  <3> fragment标签所对应Fragment的实现类。
  <4> com.eoe.tampletfragment.fragment.FragmentIndicator标签所对应的是底部导航栏。   
5、自定义顶部工具栏,TitleView.java:
  1. package com.eoe.tampletfragment.view;

  2. import android.content.Context;
  3. import android.util.AttributeSet;
  4. import android.view.LayoutInflater;
  5. import android.view.View;
  6. import android.widget.Button;
  7. import android.widget.FrameLayout;
  8. import android.widget.TextView;

  9. import com.eoe.tampletfragment.R;

  10. /**
  11. * @author yangyu
  12. *        功能描述:自定义顶部工具栏
  13. */
  14. public class TitleView extends FrameLayout implements View.OnClickListener {

  15.         private Button mLeftBtn;
  16.         private Button mRightBtn;
  17.         private TextView mTitle;

  18.         private OnLeftButtonClickListener mOnLeftButtonClickListener;
  19.         private OnRightButtonClickListener mOnRightButtonClickListener;

  20.         public interface OnLeftButtonClickListener {
  21.                 public void onClick(View button);
  22.         }

  23.         public interface OnRightButtonClickListener {
  24.                 public void onClick(View button);
  25.         }

  26.         public void setLeftButton(String text, OnLeftButtonClickListener listener) {
  27.                 mLeftBtn.setText(text);
  28.                 mLeftBtn.setVisibility(View.VISIBLE);
  29.                 mOnLeftButtonClickListener = listener;
  30.         }
  31.         
  32.         public void setLeftButton(int stringID, OnLeftButtonClickListener listener) {
  33.                 mLeftBtn.setText(stringID);
  34.                 mLeftBtn.setVisibility(View.VISIBLE);
  35.                 mOnLeftButtonClickListener = listener;
  36.         }
  37.         
  38.         public void removeLeftButton() {
  39.                 mLeftBtn.setText("");
  40.                 mLeftBtn.setVisibility(View.INVISIBLE);
  41.                 mOnLeftButtonClickListener = null;
  42.         }
  43.         
  44.         public void hiddenLeftButton() {
  45.                 mLeftBtn.setVisibility(View.INVISIBLE);
  46.         }
  47.         
  48.         public void showLeftButton() {
  49.                 mLeftBtn.setVisibility(View.VISIBLE);
  50.         }
  51.         
  52.         public void setRightButton(String text, OnRightButtonClickListener listener) {
  53.                 mRightBtn.setText(text);
  54.                 mRightBtn.setVisibility(View.VISIBLE);
  55.                 mOnRightButtonClickListener = listener;
  56.         }
  57.         
  58.         public void setRightButton(int stringID, OnRightButtonClickListener listener) {
  59.                 mRightBtn.setText(stringID);
  60.                 mRightBtn.setVisibility(View.VISIBLE);
  61.                 mOnRightButtonClickListener = listener;
  62.         }
  63.         
  64.         public void removeRightButton() {
  65.                 mRightBtn.setText("");
  66.                 mRightBtn.setVisibility(View.INVISIBLE);
  67.                 mOnRightButtonClickListener = null;
  68.         }
  69.         
  70.         public void hiddenRightButton() {
  71.                 mRightBtn.setVisibility(View.INVISIBLE);
  72.         }
  73.         
  74.         public void showRightButton() {
  75.                 mRightBtn.setVisibility(View.VISIBLE);
  76.         }

  77.         public TitleView(Context context) {
  78.                 this(context, null);
  79.         }

  80.         public TitleView(Context context, AttributeSet attrs) {
  81.                 this(context, attrs, 0);
  82.         }

  83.         public TitleView(Context context, AttributeSet attrs, int defStyle) {
  84.                 super(context, attrs, defStyle);

  85.                 LayoutInflater inflater = (LayoutInflater) context
  86.                                 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  87.                 inflater.inflate(R.layout.title_view, this, true);

  88.                 mLeftBtn = (Button) findViewById(R.id.left_btn);
  89.                 mLeftBtn.setVisibility(View.INVISIBLE);
  90.                 mLeftBtn.setOnClickListener(this);
  91.                 mRightBtn = (Button) findViewById(R.id.right_btn);
  92.                 mRightBtn.setVisibility(View.INVISIBLE);
  93.                 mRightBtn.setOnClickListener(this);
  94.                 
  95.                 mTitle = (TextView) findViewById(R.id.title_text);
  96.                 mTitle.setVisibility(View.INVISIBLE);
  97.         }
  98.         
  99.         public void setTitle(String text) {
  100.                 mTitle.setVisibility(View.VISIBLE);
  101.                 mTitle.setText(text);
  102.         }
  103.         
  104.         public void setTitle(int stringID) {
  105.                 mTitle.setVisibility(View.VISIBLE);
  106.                 mTitle.setText(stringID);
  107.         }

  108.         @Override
  109.         public void onClick(View v) {
  110.                 switch (v.getId()) {
  111.                 case R.id.left_btn:
  112.                         if(mOnLeftButtonClickListener != null)
  113.                                 mOnLeftButtonClickListener.onClick(v);
  114.                         break;
  115.                 case R.id.right_btn:
  116.                         if(mOnRightButtonClickListener != null)
  117.                                 mOnRightButtonClickListener.onClick(v);
  118.                         break;
  119.                 }
  120.         }

  121. }
复制代码
6、自定义底部工具栏,FragmentIndicator.java:
  1. package com.eoe.tampletfragment.fragment;

  2. import android.content.Context;
  3. import android.graphics.Color;
  4. import android.util.AttributeSet;
  5. import android.util.TypedValue;
  6. import android.view.Gravity;
  7. import android.view.View;
  8. import android.view.View.OnClickListener;
  9. import android.widget.ImageView;
  10. import android.widget.LinearLayout;
  11. import android.widget.TextView;

  12. import com.eoe.tampletfragment.R;

  13. /**
  14. * @author yangyu
  15. *        功能描述:自定义底部工具栏
  16. */
  17. public class FragmentIndicator extends LinearLayout implements OnClickListener {

  18.         private int mDefaultIndicator = 0;

  19.         private static int mCurIndicator;

  20.         private static View[] mIndicators;

  21.         private OnIndicateListener mOnIndicateListener;

  22.         private static final String TAG_ICON_0 = "icon_tag_0";
  23.         private static final String TAG_ICON_1 = "icon_tag_1";
  24.         private static final String TAG_ICON_2 = "icon_tag_2";

  25.         private static final String TAG_TEXT_0 = "text_tag_0";
  26.         private static final String TAG_TEXT_1 = "text_tag_1";
  27.         private static final String TAG_TEXT_2 = "text_tag_2";
  28.         
  29.         private static final int COLOR_UNSELECT = Color.argb(100, 0xff, 0xff, 0xff);
  30.         private static final int COLOR_SELECT = Color.WHITE;

  31.         private FragmentIndicator(Context context) {
  32.                 super(context);
  33.         }

  34.         public FragmentIndicator(Context context, AttributeSet attrs) {
  35.                 super(context, attrs);

  36.                 mCurIndicator = mDefaultIndicator;
  37.                 setOrientation(LinearLayout.HORIZONTAL);
  38.                 init();
  39.         }

  40.         private View createIndicator(int iconResID, int stringResID, int stringColor, 
  41.                         String iconTag, String textTag) {
  42.                 LinearLayout view = new LinearLayout(getContext());
  43.                 view.setOrientation(LinearLayout.VERTICAL);
  44.                 view.setLayoutParams(new LinearLayout.LayoutParams(
  45.                                 LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1));
  46.                 view.setGravity(Gravity.CENTER_HORIZONTAL);

  47.                 ImageView iconView = new ImageView(getContext());
  48.                 iconView.setTag(iconTag);
  49.                 iconView.setLayoutParams(new LinearLayout.LayoutParams(
  50.                                 LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1));
  51.                 iconView.setImageResource(iconResID);

  52.                 TextView textView = new TextView(getContext());
  53.                 textView.setTag(textTag);
  54.                 textView.setLayoutParams(new LinearLayout.LayoutParams(
  55.                                 LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1));
  56.                 textView.setTextColor(stringColor);
  57.                 textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
  58.                 textView.setText(stringResID);

  59.                 view.addView(iconView);
  60.                 view.addView(textView);

  61.                 return view;

  62.         }

  63.         private void init() {
  64.                 mIndicators = new View[3];
  65.                 mIndicators[0] = createIndicator(R.drawable.ic_home_focused,
  66.                                 R.string.tab_home, COLOR_SELECT, TAG_ICON_0, TAG_TEXT_0);
  67.                 mIndicators[0].setBackgroundResource(R.drawable.indic_select);
  68.                 mIndicators[0].setTag(Integer.valueOf(0));
  69.                 mIndicators[0].setOnClickListener(this);
  70.                 addView(mIndicators[0]);
  71.                 mIndicators[1] = createIndicator(R.drawable.ic_search_normal,
  72.                                 R.string.tab_search, COLOR_UNSELECT, TAG_ICON_1, TAG_TEXT_1);
  73.                 mIndicators[1].setBackgroundColor(Color.alpha(0));
  74.                 mIndicators[1].setTag(Integer.valueOf(1));
  75.                 mIndicators[1].setOnClickListener(this);
  76.                 addView(mIndicators[1]);
  77.                 mIndicators[2] = createIndicator(R.drawable.ic_settings_normal,
  78.                                 R.string.tab_settings, COLOR_UNSELECT, TAG_ICON_2, TAG_TEXT_2);
  79.                 mIndicators[2].setBackgroundColor(Color.alpha(0));
  80.                 mIndicators[2].setTag(Integer.valueOf(2));
  81.                 mIndicators[2].setOnClickListener(this);
  82.                 addView(mIndicators[2]);
  83.         }

  84.         public static void setIndicator(int which) {
  85.                 // clear previous status.
  86.                 mIndicators[mCurIndicator].setBackgroundColor(Color.alpha(0));
  87.                 ImageView prevIcon;
  88.                 TextView prevText;
  89.                 switch(mCurIndicator) {
  90.                 case 0:
  91.                         prevIcon =(ImageView) mIndicators[mCurIndicator].findViewWithTag(TAG_ICON_0);
  92.                         prevIcon.setImageResource(R.drawable.ic_home_normal);
  93.                         prevText = (TextView) mIndicators[mCurIndicator].findViewWithTag(TAG_TEXT_0);
  94.                         prevText.setTextColor(COLOR_UNSELECT);
  95.                         break;
  96.                 case 1:
  97.                         prevIcon =(ImageView) mIndicators[mCurIndicator].findViewWithTag(TAG_ICON_1);
  98.                         prevIcon.setImageResource(R.drawable.ic_search_normal);
  99.                         prevText = (TextView) mIndicators[mCurIndicator].findViewWithTag(TAG_TEXT_1);
  100.                         prevText.setTextColor(COLOR_UNSELECT);
  101.                         break;
  102.                 case 2:
  103.                         prevIcon =(ImageView) mIndicators[mCurIndicator].findViewWithTag(TAG_ICON_2);
  104.                         prevIcon.setImageResource(R.drawable.ic_settings_normal);
  105.                         prevText = (TextView) mIndicators[mCurIndicator].findViewWithTag(TAG_TEXT_2);
  106.                         prevText.setTextColor(COLOR_UNSELECT);
  107.                         break;
  108.                 }
  109.                 
  110.                 // update current status.
  111.                 mIndicators[which].setBackgroundResource(R.drawable.indic_select);
  112.                 ImageView currIcon;
  113.                 TextView currText;
  114.                 switch(which) {
  115.                 case 0:
  116.                         currIcon =(ImageView) mIndicators[which].findViewWithTag(TAG_ICON_0);
  117.                         currIcon.setImageResource(R.drawable.ic_home_focused);
  118.                         currText = (TextView) mIndicators[which].findViewWithTag(TAG_TEXT_0);
  119.                         currText.setTextColor(COLOR_SELECT);
  120.                         break;
  121.                 case 1:
  122.                         currIcon =(ImageView) mIndicators[which].findViewWithTag(TAG_ICON_1);
  123.                         currIcon.setImageResource(R.drawable.ic_search_focused);
  124.                         currText = (TextView) mIndicators[which].findViewWithTag(TAG_TEXT_1);
  125.                         currText.setTextColor(COLOR_SELECT);
  126.                         break;
  127.                 case 2:
  128.                         currIcon =(ImageView) mIndicators[which].findViewWithTag(TAG_ICON_2);
  129.                         currIcon.setImageResource(R.drawable.ic_settings_focused);
  130.                         currText = (TextView) mIndicators[which].findViewWithTag(TAG_TEXT_2);
  131.                         currText.setTextColor(COLOR_SELECT);
  132.                         break;
  133.                 }
  134.                 
  135.                 mCurIndicator = which;
  136.         }

  137.         public interface OnIndicateListener {
  138.                 public void onIndicate(View v, int which);
  139.         }

  140.         public void setOnIndicateListener(OnIndicateListener listener) {
  141.                 mOnIndicateListener = listener;
  142.         }

  143.         @Override
  144.         public void onClick(View v) {
  145.                 if (mOnIndicateListener != null) {
  146.                         int tag = (Integer) v.getTag();
  147.                         switch (tag) {
  148.                         case 0:
  149.                                 if (mCurIndicator != 0) {
  150.                                         mOnIndicateListener.onIndicate(v, 0);
  151.                                         setIndicator(0);
  152.                                 }
  153.                                 break;
  154.                         case 1:
  155.                                 if (mCurIndicator != 1) {
  156.                                         mOnIndicateListener.onIndicate(v, 1);
  157.                                         setIndicator(1);
  158.                                 }
  159.                                 break;
  160.                         case 2:
  161.                                 if (mCurIndicator != 2) {
  162.                                         mOnIndicateListener.onIndicate(v, 2);
  163.                                         setIndicator(2);
  164.                                 }
  165.                                 break;
  166.                         default:
  167.                                 break;
  168.                         }
  169.                 }
  170.         }
  171. }
复制代码
7、首页fragment页面,HomeFragment.java:
  1. package com.eoe.tampletfragment.fragment;

  2. import android.content.Intent;
  3. import android.os.Bundle;
  4. import android.support.v4.app.Fragment;
  5. import android.support.v4.app.FragmentActivity;
  6. import android.view.LayoutInflater;
  7. import android.view.View;
  8. import android.view.ViewGroup;
  9. import android.widget.TextView;

  10. import com.eoe.tampletfragment.HelpActivity;
  11. import com.eoe.tampletfragment.R;
  12. import com.eoe.tampletfragment.view.TitleView;
  13. import com.eoe.tampletfragment.view.TitleView.OnLeftButtonClickListener;
  14. import com.eoe.tampletfragment.view.TitleView.OnRightButtonClickListener;

  15. /**
  16. * @author yangyu
  17. *        功能描述:首页fragment页面
  18. */
  19. public class HomeFragment extends Fragment {

  20.         private View mParent;
  21.         
  22.         private FragmentActivity mActivity;
  23.         
  24.         private TitleView mTitle;
  25.         
  26.         private TextView mText;
  27.         
  28.         /**
  29.          * Create a new instance of DetailsFragment, initialized to show the text at
  30.          * 'index'.
  31.          */
  32.         public static HomeFragment newInstance(int index) {
  33.                 HomeFragment f = new HomeFragment();

  34.                 // Supply index input as an argument.
  35.                 Bundle args = new Bundle();
  36.                 args.putInt("index", index);
  37.                 f.setArguments(args);

  38.                 return f;
  39.         }

  40.         public int getShownIndex() {
  41.                 return getArguments().getInt("index", 0);
  42.         }

  43.         @Override
  44.         public View onCreateView(LayoutInflater inflater, ViewGroup container,
  45.                         Bundle savedInstanceState) {
  46.                 View view = inflater.inflate(R.layout.fragment_home, container, false);
  47.                 return view;
  48.         }

  49.         @Override
  50.         public void onActivityCreated(Bundle savedInstanceState) {
  51.                 super.onActivityCreated(savedInstanceState);
  52.                 mActivity = getActivity();
  53.                 mParent = getView();

  54.                 mTitle = (TitleView) mParent.findViewById(R.id.title);
  55.                 mTitle.setTitle(R.string.title_home);
  56.                 mTitle.setLeftButton(R.string.exit, new OnLeftButtonClickListener(){

  57.                         @Override
  58.                         public void onClick(View button) {
  59.                                 mActivity.finish();
  60.                         }
  61.                         
  62.                 });
  63.                 mTitle.setRightButton(R.string.help, new OnRightButtonClickListener() {

  64.                         @Override
  65.                         public void onClick(View button) {
  66.                                 goHelpActivity();
  67.                         }
  68.                 });
  69.                 
  70.                 mText = (TextView) mParent.findViewById(R.id.fragment_home_text);

  71.         }
  72.         
  73.         private void goHelpActivity() {
  74.                 Intent intent = new Intent(mActivity, HelpActivity.class);
  75.                 startActivity(intent);
  76.         }

  77.         @Override
  78.         public void onHiddenChanged(boolean hidden) {
  79.                 super.onHiddenChanged(hidden);
  80.         }

  81.         @Override
  82.         public void onDestroy() {
  83.                 super.onDestroy();
  84.         }

  85. }
复制代码
8、Activity帮助界面,HelpActivity.java:
  1. package com.eoe.tampletfragment;

  2. import android.os.Bundle;
  3. import android.support.v4.app.FragmentActivity;
  4. import android.view.Window;

  5. /**
  6. * @author yangyu
  7. *        功能描述:帮助Activity界面
  8. */
  9. public class HelpActivity extends FragmentActivity {

  10.         @Override
  11.         protected void onCreate(Bundle savedInstanceState) {
  12.                 super.onCreate(savedInstanceState);
  13.                 requestWindowFeature(Window.FEATURE_NO_TITLE);        
  14.                 setContentView(R.layout.activity_help);
  15.         }

  16. }
复制代码
9、Activity主界面,MainActivity.java:
  1. package com.eoe.tampletfragment;

  2. import android.os.Bundle;
  3. import android.support.v4.app.Fragment;
  4. import android.support.v4.app.FragmentActivity;
  5. import android.view.View;
  6. import android.view.Window;

  7. import com.eoe.tampletfragment.fragment.FragmentIndicator;
  8. import com.eoe.tampletfragment.fragment.FragmentIndicator.OnIndicateListener;

  9. /**
  10. * @author yangyu
  11. *        功能描述:主Activity类,继承自FragmentActivity
  12. */
  13. public class MainActivity extends FragmentActivity {

  14.         public static Fragment[] mFragments;

  15.         @Override
  16.         protected void onCreate(Bundle savedInstanceState) {
  17.                 super.onCreate(savedInstanceState);
  18.                 requestWindowFeature(Window.FEATURE_NO_TITLE);
  19.                 setContentView(R.layout.activity_main);

  20.                 setFragmentIndicator(0);
  21.                 
  22.         }

  23.         /**
  24.          * 初始化fragment
  25.          */
  26.         private void setFragmentIndicator(int whichIsDefault) {
  27.                 mFragments = new Fragment[3];
  28.                 mFragments[0] = getSupportFragmentManager().findFragmentById(R.id.fragment_home);
  29.                 mFragments[1] = getSupportFragmentManager().findFragmentById(R.id.fragment_search);
  30.                 mFragments[2] = getSupportFragmentManager().findFragmentById(R.id.fragment_settings);
  31.                 getSupportFragmentManager().beginTransaction().hide(mFragments[0])
  32.                                 .hide(mFragments[1]).hide(mFragments[2]).show(mFragments[whichIsDefault]).commit();

  33.                 FragmentIndicator mIndicator = (FragmentIndicator) findViewById(R.id.indicator);
  34.                 FragmentIndicator.setIndicator(whichIsDefault);
  35.                 mIndicator.setOnIndicateListener(new OnIndicateListener() {
  36.                         @Override
  37.                         public void onIndicate(View v, int which) {
  38.                                 getSupportFragmentManager().beginTransaction()
  39.                                                 .hide(mFragments[0]).hide(mFragments[1])
  40.                                                 .hide(mFragments[2]).show(mFragments[which]).commit();
  41.                         }
  42.                 });
  43.         }

  44.         @Override
  45.         protected void onResume() {
  46.                 super.onResume();
  47.         }
  48.         
  49.         @Override
  50.         protected void onPause() {
  51.                 super.onPause();
  52.         }
  53.         
  54. }
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值