转android的UI设计七

转载请注明出处: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 plain copy
  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 plain copy
  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 plain copy
  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 plain copy
  1. FragmentManager fragmentManager = getFragmentManager();  
  2. FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();  

 

一个事务是在同一时刻执行的一组动作(很像数据库中的事务)。可以用add(),remove(),replace()等方法构成事务

,最后使用commit()方法提交事务。在调用commit()之前,可以用addToBackStack()把事务添加到一个后退栈中,这

个后退栈属于所在的activity。有了它,就可以在用户按下返回键时,返回到fragment执行事务之前的状态。如下例:

演示了如何用一个fragment代替另一个fragment,同时在后退栈中保存被代替的fragment的状态。

[java]  view plain copy
  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 plain copy
  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 plain copy
  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 plain copy
  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 plain copy
  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 plain copy
  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 plain copy
  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 plain copy
  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 plain copy
  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 plain copy
  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 plain copy
  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 plain copy
  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 plain copy
  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 plain copy
  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 plain copy
  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 plain copy
  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 plain copy
  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 plain copy
  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 plain copy
  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 plain copy
  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 plain copy
  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. }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值