转载请注明出处: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. <spanstyle="font-size:10px;">publicstaticExampleFragmentextendsFragment{
  2. @Override
  3. publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,
  4. BundlesavedInstanceState){
  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. FragmentManagerfragmentManager=getFragmentManager();
  2. FragmentTransactionfragmentTransaction=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. FragmentManagerfragmentManager=getFragmentManager();
  2. FragmentTransactionfragmentTransaction=fragmentManager.beginTransaction();

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

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

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

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

[java] view plain copy
  1. //创建一个fragment
  2. FragmentnewFragment=newExampleFragment();
  3. //实例化fragment事务管理器
  4. FragmentTransactiontransaction=getFragmentManager().beginTransaction();
  5. //用新创建的fragment来代替fragment_container
  6. transaction.replace(R.id.fragment_container,newFragment);
  7. //添加进栈中
  8. transaction.addToBackStack(null);
  9. //提交事务
  10. 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. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns: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:

[html] view plain copy
  1. <spanstyle="font-size:12px;"><?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns: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. <includelayout="@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. <includelayout="@layout/wifi"/>
  22. </RelativeLayout>
  23. </LinearLayout></span>

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

[html] view plain copy
  1. <LinearLayoutxmlns: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:

[html] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns: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="LargeText"
  16. android:textAppearance="?android:attr/textAppearanceLarge"/>
  17. </LinearLayout>

5、save.xml:

[html] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns: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:

[html] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns: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:

[html] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <RelativeLayoutxmlns: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:

[java] view plain copy
  1. packageco.cm.fragement;
  2. importco.cm.fragement.R;
  3. importandroid.app.Activity;
  4. importandroid.content.Context;
  5. importandroid.os.Bundle;
  6. publicclassAndroidFragmentActivityextendsActivity{
  7. //主activity
  8. @Override
  9. publicvoidonCreate(BundlesavedInstanceState){
  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:

[java] view plain copy
  1. packageco.cm.fragement;
  2. importco.cm.fragement.R;
  3. importandroid.app.Fragment;
  4. importandroid.os.Bundle;
  5. importandroid.os.Handler;
  6. importandroid.os.Message;
  7. importandroid.util.Log;
  8. importandroid.view.LayoutInflater;
  9. importandroid.view.View;
  10. importandroid.view.View.OnClickListener;
  11. importandroid.view.ViewGroup;
  12. importandroid.widget.CompoundButton;
  13. importandroid.widget.CompoundButton.OnCheckedChangeListener;
  14. importandroid.widget.LinearLayout;
  15. importandroid.widget.TextView;
  16. importandroid.widget.ToggleButton;
  17. /**
  18. *@authoryuyang
  19. *功能描述:左面fragment界面类,该类提供了选项操作
  20. */
  21. publicclassFragementListextendsFragment{
  22. //点击切换到wifi存储界面
  23. privateTextViewwifi;
  24. //点击切换到save存储界面
  25. privateTextViewsaveBut;
  26. //定义右面fragment实例
  27. privateFragementDetailsfrag_detail;
  28. //打开关闭wifi按钮
  29. privateToggleButtontoggleButton;
  30. //toggleButton按钮是否被点击
  31. privatebooleanisChecked=false;
  32. //监听button状态线程标志位
  33. privatebooleanbutIsRunning=false;
  34. @Override
  35. publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,BundlesavedInstanceState){
  36. //在这里初始化fragment的页面
  37. returninflater.inflate(R.layout.frag_list,container,false);
  38. }
  39. @Override
  40. publicvoidonActivityCreated(BundlesavedInstanceState){
  41. super.onActivityCreated(savedInstanceState);
  42. //由于fragment不是activity,不是oncreated,而是onActivityCreated
  43. setView();
  44. setListener();
  45. startThread();//启动控制button的线程,当wifi状态不是在1或者3的时候,不可点击,
  46. //if(frag!=null&&frag.isInLayout()){
  47. //switch(arg2){
  48. //case0:
  49. //frag.setText("0000");
  50. }
  51. /**
  52. *给按钮设置监听
  53. */
  54. publicvoidsetListener(){
  55. saveBut.setOnClickListener(newOnClickListener(){
  56. @Override
  57. publicvoidonClick(Viewv){
  58. frag_detail.setSaveShow();
  59. }
  60. });
  61. wifi.setOnClickListener(newOnClickListener(){
  62. @Override
  63. publicvoidonClick(Viewv){
  64. frag_detail.setWifiShow();
  65. Log.i("111",WifiAdmin.getWifiAdmin().checkState()+"===-=-");
  66. checktoggleButton();//当点回到wifi界面时,刷新button的状态
  67. }
  68. });
  69. toggleButton.setOnClickListener(newOnClickListener(){
  70. @Override
  71. publicvoidonClick(Viewv){
  72. Log.i("111",isChecked+"/"+WifiAdmin.getWifiAdmin().checkState());
  73. if(isChecked){
  74. WifiAdmin.getWifiAdmin().OpenWifi();
  75. frag_detail.setWifiShow();
  76. //toggleButton.setText("关闭");
  77. toggleButton.setChecked(false);
  78. isChecked=false;
  79. }else{
  80. WifiAdmin.getWifiAdmin().CloseWife();
  81. frag_detail.setWifiShow();
  82. //toggleButton.setText("打开");
  83. toggleButton.setChecked(true);
  84. isChecked=true;
  85. }
  86. toggleButton.setClickable(false);
  87. }
  88. });
  89. }
  90. //
  91. publicvoidchecktoggleButton(){
  92. if(WifiAdmin.getWifiAdmin().checkState()==1){
  93. toggleButton.setChecked(true);
  94. isChecked=true;
  95. }
  96. if(WifiAdmin.getWifiAdmin().checkState()==3){
  97. toggleButton.setChecked(false);
  98. isChecked=false;
  99. }
  100. }
  101. publicvoidsetView(){
  102. wifi=(TextView)getView().findViewById(R.id.wifi);
  103. toggleButton=(ToggleButton)getView().findViewById(R.id.toggleButton);
  104. saveBut=(TextView)getView().findViewById(R.id.saveBut);
  105. //实例化右面界面,以便操纵里面的方法F
  106. frag_detail=(FragementDetails)getFragmentManager().findFragmentById(R.id.frag_detail);
  107. //初始化button的装态
  108. if(WifiAdmin.getWifiAdmin().checkState()==3){
  109. toggleButton.setChecked(false);
  110. isChecked=false;
  111. }
  112. if(WifiAdmin.getWifiAdmin().checkState()==1){
  113. toggleButton.setChecked(true);
  114. isChecked=true;
  115. }
  116. toggleButton.setClickable(true);
  117. }
  118. @Override
  119. publicvoidonDestroy(){
  120. frag_detail.stopWifiThread();
  121. butIsRunning=false;
  122. super.onDestroy();
  123. }
  124. privatevoidstartThread(){
  125. butIsRunning=true;
  126. newThread(newRunnable(){
  127. @Override
  128. publicvoidrun(){
  129. while(butIsRunning){
  130. //只有wifi状态改变变化完毕之后才能允许点击按钮
  131. if(WifiAdmin.getWifiAdmin().checkState()==3){
  132. if(!isChecked){
  133. toggleButton.setClickable(true);
  134. }
  135. }elseif(WifiAdmin.getWifiAdmin().checkState()==1){
  136. if(isChecked){
  137. toggleButton.setClickable(true);
  138. }
  139. }
  140. }
  141. }
  142. }).start();
  143. }
  144. }

10、右面fragment界面类

[java] view plain copy
  1. packageco.cm.fragement;
  2. importjava.util.ArrayList;
  3. importjava.util.List;
  4. importco.cm.fragement.R;
  5. importandroid.app.Fragment;
  6. importandroid.net.wifi.ScanResult;
  7. importandroid.net.wifi.WifiConfiguration;
  8. importandroid.os.Bundle;
  9. importandroid.os.Handler;
  10. importandroid.os.Message;
  11. importandroid.util.Log;
  12. importandroid.view.LayoutInflater;
  13. importandroid.view.View;
  14. importandroid.view.ViewGroup;
  15. importandroid.widget.BaseAdapter;
  16. importandroid.widget.LinearLayout;
  17. importandroid.widget.ListView;
  18. importandroid.widget.RelativeLayout;
  19. importandroid.widget.TextView;
  20. /**
  21. *@authoryangyu
  22. *功能描述:右面fragment界面类,该类实现了右面显示的操作
  23. */
  24. publicclassFragementDetailsextendsFragment{
  25. privateTextViewmac_address,bssid,ip_address,id,info,wifiText;
  26. privateListViewlistView;
  27. privateLinearLayoutwifiLinear;
  28. privateRelativeLayoutsave,wifi;
  29. privatebooleanThreadFlag=false;
  30. //wifi数据适配器
  31. privateWifiAdapterwifiAdapter;
  32. //扫描出的网络连接列表
  33. privateList<ScanResult>mWifiList=newArrayList<ScanResult>();
  34. //网络连接列表
  35. privateList<WifiConfiguration>mWifiConfiguration=null;
  36. privateintnowWifiState=0;
  37. @Override
  38. publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,BundlesavedInstanceState){
  39. returninflater.inflate(R.layout.frag_detail,container,false);
  40. }
  41. @Override
  42. publicvoidonActivityCreated(BundlesavedInstanceState){
  43. super.onActivityCreated(savedInstanceState);
  44. setView();
  45. //setListener();
  46. setWifiShow();
  47. }
  48. /**
  49. *显示wifi界面
  50. */
  51. publicvoidsetWifiShow(){
  52. //通过隐藏显示来达到不同页面内容的切换
  53. save.setVisibility(View.GONE);
  54. wifi.setVisibility(View.VISIBLE);
  55. stopWifiThread();
  56. refreshWifi();
  57. }
  58. /**
  59. *显示保存界面
  60. */
  61. publicvoidsetSaveShow(){
  62. stopWifiThread();
  63. save.setVisibility(View.VISIBLE);
  64. wifi.setVisibility(View.GONE);
  65. }
  66. /**
  67. *初始化组件
  68. */
  69. publicvoidsetView(){
  70. //-----------------wifi-----------------
  71. wifiText=(TextView)getView().findViewById(R.id.wifiText);
  72. mac_address=(TextView)getView().findViewById(R.id.mac_address);
  73. bssid=(TextView)getView().findViewById(R.id.bssid);
  74. ip_address=(TextView)getView().findViewById(R.id.ip_address);
  75. id=(TextView)getView().findViewById(R.id.id);
  76. info=(TextView)getView().findViewById(R.id.info);
  77. listView=(ListView)getView().findViewById(R.id.listview);
  78. wifiLinear=(LinearLayout)getView().findViewById(R.id.wifiLinear);
  79. save=(RelativeLayout)getView().findViewById(R.id.save);
  80. wifi=(RelativeLayout)getView().findViewById(R.id.wifi);
  81. wifiAdapter=newWifiAdapter();
  82. listView.setAdapter(wifiAdapter);
  83. }
  84. privateHandlerhandler=newHandler(){
  85. @Override
  86. publicvoidhandleMessage(Messagemsg){
  87. nowWifiState=WifiAdmin.getWifiAdmin().checkState();
  88. //当wifi打开时,刷新wifi列表的内容
  89. if(nowWifiState==3){
  90. mWifiList=WifiAdmin.getWifiAdmin().GetWifiList();
  91. //如果刚开始检测的wifi列表为空,则创建一个实例化的wifi而不是null,负责会在adpter里面报错
  92. if(mWifiList!=null){
  93. //如果wifi列表发生改变,则更新,else不更新
  94. if(!mWifiList.toString().equals(
  95. WifiAdmin.getWifiAdmin().getLastWifiList().toString())){
  96. WifiAdmin.getWifiAdmin().setLastWifiList(mWifiList);
  97. wifiAdapter.notifyDate();
  98. }
  99. }else{
  100. mWifiList=newArrayList<ScanResult>();
  101. }
  102. }
  103. refreshMeathod();
  104. super.handleMessage(msg);
  105. }
  106. };
  107. /**
  108. *刷新wifi的状态
  109. */
  110. publicvoidrefreshWifi(){
  111. newThread(newRunnable(){
  112. @Override
  113. publicvoidrun(){
  114. ThreadFlag=true;
  115. while(ThreadFlag){
  116. //Log.i("111",WifiAdmin.getWifiAdmin().checkState()+
  117. //"!!!");
  118. Messagemsg=handler.obtainMessage();
  119. handler.sendMessage(msg);
  120. try{
  121. Thread.sleep(1000);
  122. }catch(InterruptedExceptione){
  123. e.printStackTrace();
  124. }
  125. }
  126. }
  127. }).start();
  128. }
  129. publicvoidrefreshMeathod(){
  130. //此处可用switch
  131. if(nowWifiState==3){
  132. wifiLinear.setVisibility(View.VISIBLE);
  133. wifiText.setVisibility(View.INVISIBLE);
  134. mac_address.setText(WifiAdmin.getWifiAdmin().GetMacAddress()+"");
  135. bssid.setText(WifiAdmin.getWifiAdmin().GetBSSID()+"");
  136. ip_address.setText(WifiAdmin.getWifiAdmin().GetIPAddress()+"");
  137. id.setText(WifiAdmin.getWifiAdmin().GetNetworkId()+"");
  138. info.setText(WifiAdmin.getWifiAdmin().GetWifiInfo()+"");
  139. }elseif(nowWifiState==1){
  140. wifiText.setVisibility(View.VISIBLE);
  141. wifiLinear.setVisibility(View.INVISIBLE);
  142. wifiText.setText("要查看可用的网络,请打开wifi");
  143. }elseif(nowWifiState==2){
  144. wifiText.setVisibility(View.VISIBLE);
  145. wifiLinear.setVisibility(View.INVISIBLE);
  146. wifiText.setText("wifi正在打开");
  147. }elseif(nowWifiState==4){
  148. wifiText.setVisibility(View.VISIBLE);
  149. wifiLinear.setVisibility(View.INVISIBLE);
  150. wifiText.setText("wifi正在关闭");
  151. }else{
  152. wifiText.setVisibility(View.VISIBLE);
  153. wifiLinear.setVisibility(View.INVISIBLE);
  154. wifiText.setText("我不知道wifi正在做什么");
  155. }
  156. }
  157. publicvoidstopWifiThread(){
  158. ThreadFlag=false;
  159. }
  160. publicclassWifiAdapterextendsBaseAdapter{
  161. @Override
  162. publicintgetCount(){
  163. returnmWifiList.size();
  164. }
  165. @Override
  166. publicObjectgetItem(intposition){
  167. returnmWifiList.get(position);
  168. }
  169. @Override
  170. publiclonggetItemId(intposition){
  171. returnposition;
  172. }
  173. @Override
  174. publicViewgetView(intposition,ViewconvertView,ViewGroupparent){
  175. Viewview=convertView;
  176. finalChatViewHoldervh;
  177. if(convertView==null){
  178. vh=newChatViewHolder();
  179. view=View.inflate(WifiAdmin.getWifiAdmin().getmContext(),
  180. R.layout.wifi_list,null);
  181. vh.wifi_name=(TextView)view.findViewById(R.id.wifi_name);
  182. vh.wifi_name_state=(TextView)view
  183. .findViewById(R.id.wifi_name_state);
  184. view.setTag(vh);
  185. }else{
  186. vh=(ChatViewHolder)view.getTag();
  187. }
  188. vh.wifi_name.setText(mWifiList.get(position).SSID.toString());//网络的名字,唯一区别WIFI网络的名字
  189. vh.wifi_name_state.setText(mWifiList.get(position).level+"");
  190. returnview;
  191. }
  192. publicvoidnotifyDate(){
  193. notifyDataSetChanged();
  194. }
  195. }
  196. publicclassChatViewHolder{
  197. TextViewwifi_name;//网络的名字,唯一区别WIFI网络的名字
  198. TextViewwifi_name_state;//所发现的WIFI网络信号强度
  199. }
  200. }

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

[java] view plain copy
  1. packageco.cm.fragement;
  2. importjava.util.ArrayList;
  3. importjava.util.List;
  4. importandroid.content.Context;
  5. importandroid.net.wifi.ScanResult;
  6. importandroid.net.wifi.WifiConfiguration;
  7. importandroid.net.wifi.WifiInfo;
  8. importandroid.net.wifi.WifiManager;
  9. importandroid.net.wifi.WifiManager.WifiLock;
  10. importandroid.util.Log;
  11. /**
  12. *@authoryangyu
  13. *wifiAdmin提供了wifi操作的方法
  14. */
  15. publicclassWifiAdmin{
  16. privatestaticWifiAdminwifiAdmin;
  17. privateWifiManagermWifiManager=null;
  18. privateWifiInfomWifiInfo=null;
  19. //扫描出的网络连接列表
  20. privateList<ScanResult>mWifiList=newArrayList<ScanResult>();
  21. //扫描出的网络连接列表
  22. privateList<ScanResult>lastWifiList=newArrayList<ScanResult>();
  23. //网络连接列表
  24. privateList<WifiConfiguration>mWifiConfiguration=null;
  25. privateWifiLockmWifiLock=null;
  26. //上次网络状态
  27. privateintlastWifiState=0;
  28. //定义上下文Context
  29. ContextmContext;
  30. publicList<ScanResult>getLastWifiList(){
  31. returnlastWifiList;
  32. }
  33. publicvoidsetLastWifiList(List<ScanResult>lastWifiList){
  34. this.lastWifiList=lastWifiList;
  35. }
  36. publicintgetLastWifiState(){
  37. returnlastWifiState;
  38. }
  39. publicvoidsetLastWifiState(intlastWifiState){
  40. this.lastWifiState=lastWifiState;
  41. }
  42. publicstaticWifiAdmingetWifi(){
  43. returnwifiAdmin;
  44. }
  45. publicContextgetmContext(){
  46. returnmContext;
  47. }
  48. publicvoidsetmContext(ContextmContext){
  49. this.mContext=mContext;
  50. }
  51. publicstaticWifiAdmingetWifiAdmin(){
  52. if(wifiAdmin==null){
  53. wifiAdmin=newWifiAdmin();
  54. }
  55. returnwifiAdmin;
  56. }
  57. publicvoidgetWifiMeathod(){
  58. mWifiManager=(WifiManager)mContext
  59. .getSystemService(mContext.WIFI_SERVICE);
  60. mWifiInfo=mWifiManager.getConnectionInfo();
  61. }
  62. /**
  63. *打开wifi
  64. */
  65. publicvoidOpenWifi(){
  66. if(!mWifiManager.isWifiEnabled()){
  67. mWifiManager.setWifiEnabled(true);
  68. }else{
  69. Log.i("111","open失败");
  70. }
  71. }
  72. /**
  73. *关闭wifi
  74. */
  75. publicvoidCloseWife(){
  76. if(mWifiManager.isWifiEnabled()){
  77. mWifiManager.setWifiEnabled(false);
  78. }else{
  79. Log.i("111","close失败");
  80. }
  81. }
  82. /**
  83. *锁定wifi
  84. */
  85. publicvoidlockWifi(){
  86. mWifiLock.acquire();
  87. }
  88. publicvoidrlockWifi(){
  89. if(mWifiLock.isHeld()){
  90. mWifiLock.acquire();
  91. }
  92. }
  93. //检查当前wifi状态WIFI网卡的状态是由一系列的整形常量来表示的。
  94. //1.WIFI_STATE_DISABLED:WIFI网卡不可用(1)
  95. //2.WIFI_STATE_DISABLING:WIFI网卡正在关闭(0)
  96. //3.WIFI_STATE_ENABLED:WIFI网卡可用(3)
  97. //4.WIFI_STATE_ENABLING:WIFI网正在打开(2)(WIFI启动需要一段时间)
  98. //5.WIFI_STATE_UNKNOWN:未知网卡状态
  99. publicintcheckState(){
  100. returnmWifiManager.getWifiState();
  101. }
  102. /**
  103. *创建一个wifilock
  104. */
  105. publicvoidCreatewifilock(){
  106. mWifiLock=mWifiManager.createWifiLock("Testss");
  107. }
  108. /**
  109. *得到配置好的网络
  110. *@return
  111. */
  112. publicList<WifiConfiguration>GetConfinguration(){
  113. returnmWifiConfiguration;
  114. }
  115. /**
  116. *连接配置好的指定ID的网络
  117. *@paramindex
  118. */
  119. publicvoidConnectConfiguration(intindex){
  120. if(index>mWifiConfiguration.size()){
  121. return;
  122. }
  123. mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId,true);
  124. }
  125. /**
  126. *开始扫描网络
  127. */
  128. publicvoidStartScan(){
  129. mWifiManager.startScan();
  130. //得到扫描结果
  131. mWifiList=mWifiManager.getScanResults();
  132. //得到配置好的网络连接
  133. mWifiConfiguration=mWifiManager.getConfiguredNetworks();
  134. }
  135. /**
  136. *得到网络列表
  137. *@return
  138. */
  139. publicList<ScanResult>GetWifiList(){
  140. mWifiManager.startScan();
  141. //得到扫描结果
  142. mWifiList=mWifiManager.getScanResults();
  143. returnmWifiList;
  144. }
  145. publicList<WifiConfiguration>getmWifiConfiguration(){
  146. returnmWifiConfiguration;
  147. }
  148. /**
  149. *查看扫描结果
  150. */
  151. publicStringBuilderLookUpScan(){
  152. StringBuilderstringBuilder=newStringBuilder();
  153. for(inti=0;i<mWifiList.size();i++){
  154. stringBuilder.append("Index_"+newInteger(i+1).toString()+":");
  155. //将ScanResult信息转换成一个字符串包
  156. //其中把包括:BSSID、SSID、capabilities、frequency、level
  157. stringBuilder.append((mWifiList.get(i)).toString());
  158. stringBuilder.append("\n");
  159. }
  160. returnstringBuilder;
  161. }
  162. /**
  163. *得到MAC地址
  164. */
  165. publicStringGetMacAddress(){
  166. return(mWifiInfo==null)?"NULL":mWifiInfo.getMacAddress();
  167. }
  168. /**
  169. *得到接入点的BSSID
  170. */
  171. publicStringGetBSSID(){
  172. return(mWifiInfo==null)?"NULL":mWifiInfo.getBSSID();
  173. }
  174. /**
  175. *得到IP地址
  176. */
  177. publicintGetIPAddress(){
  178. return(mWifiInfo==null)?0:mWifiInfo.getIpAddress();
  179. }
  180. /**
  181. *得到连接的ID
  182. */
  183. publicintGetNetworkId(){
  184. return(mWifiInfo==null)?0:mWifiInfo.getNetworkId();
  185. }
  186. /**
  187. *得到WifiInfo的所有信息包
  188. */
  189. publicStringGetWifiInfo(){
  190. return(mWifiInfo==null)?"NULL":mWifiInfo.toString();
  191. }
  192. /**
  193. *添加一个网络并连接
  194. */
  195. publicvoidAddNetwork(WifiConfigurationwcg){
  196. intwcgID=mWifiManager.addNetwork(wcg);
  197. mWifiManager.enableNetwork(wcgID,true);
  198. }
  199. /**
  200. *断开指定ID的网络
  201. */
  202. publicvoidDisconnectWifi(intnetId){
  203. mWifiManager.disableNetwork(netId);
  204. mWifiManager.disconnect();
  205. }
  206. }

小结:当我们需要在一个界面中处理很多事情的时候,可以推荐使用fragment,因为他会把我们的activity分割成很多小块,每个小块都有他的生命周期,非常方便,而有时我们会用单例模式来存储每个页面都有的东西。


三、Fragment实例讲解二

3.1 项目的效果图

3.2 项目结构目录


3.3 代码具体编写


1、标题栏的布局界面,title_view.xml:

[html] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns: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:

[html] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns: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:

[html] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns: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:

[html] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns: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:

[java] view plain copy
  1. packagecom.eoe.tampletfragment.view;
  2. importandroid.content.Context;
  3. importandroid.util.AttributeSet;
  4. importandroid.view.LayoutInflater;
  5. importandroid.view.View;
  6. importandroid.widget.Button;
  7. importandroid.widget.FrameLayout;
  8. importandroid.widget.TextView;
  9. importcom.eoe.tampletfragment.R;
  10. /**
  11. *@authoryangyu
  12. *功能描述:自定义顶部工具栏
  13. */
  14. publicclassTitleViewextendsFrameLayoutimplementsView.OnClickListener{
  15. privateButtonmLeftBtn;
  16. privateButtonmRightBtn;
  17. privateTextViewmTitle;
  18. privateOnLeftButtonClickListenermOnLeftButtonClickListener;
  19. privateOnRightButtonClickListenermOnRightButtonClickListener;
  20. publicinterfaceOnLeftButtonClickListener{
  21. publicvoidonClick(Viewbutton);
  22. }
  23. publicinterfaceOnRightButtonClickListener{
  24. publicvoidonClick(Viewbutton);
  25. }
  26. publicvoidsetLeftButton(Stringtext,OnLeftButtonClickListenerlistener){
  27. mLeftBtn.setText(text);
  28. mLeftBtn.setVisibility(View.VISIBLE);
  29. mOnLeftButtonClickListener=listener;
  30. }
  31. publicvoidsetLeftButton(intstringID,OnLeftButtonClickListenerlistener){
  32. mLeftBtn.setText(stringID);
  33. mLeftBtn.setVisibility(View.VISIBLE);
  34. mOnLeftButtonClickListener=listener;
  35. }
  36. publicvoidremoveLeftButton(){
  37. mLeftBtn.setText("");
  38. mLeftBtn.setVisibility(View.INVISIBLE);
  39. mOnLeftButtonClickListener=null;
  40. }
  41. publicvoidhiddenLeftButton(){
  42. mLeftBtn.setVisibility(View.INVISIBLE);
  43. }
  44. publicvoidshowLeftButton(){
  45. mLeftBtn.setVisibility(View.VISIBLE);
  46. }
  47. publicvoidsetRightButton(Stringtext,OnRightButtonClickListenerlistener){
  48. mRightBtn.setText(text);
  49. mRightBtn.setVisibility(View.VISIBLE);
  50. mOnRightButtonClickListener=listener;
  51. }
  52. publicvoidsetRightButton(intstringID,OnRightButtonClickListenerlistener){
  53. mRightBtn.setText(stringID);
  54. mRightBtn.setVisibility(View.VISIBLE);
  55. mOnRightButtonClickListener=listener;
  56. }
  57. publicvoidremoveRightButton(){
  58. mRightBtn.setText("");
  59. mRightBtn.setVisibility(View.INVISIBLE);
  60. mOnRightButtonClickListener=null;
  61. }
  62. publicvoidhiddenRightButton(){
  63. mRightBtn.setVisibility(View.INVISIBLE);
  64. }
  65. publicvoidshowRightButton(){
  66. mRightBtn.setVisibility(View.VISIBLE);
  67. }
  68. publicTitleView(Contextcontext){
  69. this(context,null);
  70. }
  71. publicTitleView(Contextcontext,AttributeSetattrs){
  72. this(context,attrs,0);
  73. }
  74. publicTitleView(Contextcontext,AttributeSetattrs,intdefStyle){
  75. super(context,attrs,defStyle);
  76. LayoutInflaterinflater=(LayoutInflater)context
  77. .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  78. inflater.inflate(R.layout.title_view,this,true);
  79. mLeftBtn=(Button)findViewById(R.id.left_btn);
  80. mLeftBtn.setVisibility(View.INVISIBLE);
  81. mLeftBtn.setOnClickListener(this);
  82. mRightBtn=(Button)findViewById(R.id.right_btn);
  83. mRightBtn.setVisibility(View.INVISIBLE);
  84. mRightBtn.setOnClickListener(this);
  85. mTitle=(TextView)findViewById(R.id.title_text);
  86. mTitle.setVisibility(View.INVISIBLE);
  87. }
  88. publicvoidsetTitle(Stringtext){
  89. mTitle.setVisibility(View.VISIBLE);
  90. mTitle.setText(text);
  91. }
  92. publicvoidsetTitle(intstringID){
  93. mTitle.setVisibility(View.VISIBLE);
  94. mTitle.setText(stringID);
  95. }
  96. @Override
  97. publicvoidonClick(Viewv){
  98. switch(v.getId()){
  99. caseR.id.left_btn:
  100. if(mOnLeftButtonClickListener!=null)
  101. mOnLeftButtonClickListener.onClick(v);
  102. break;
  103. caseR.id.right_btn:
  104. if(mOnRightButtonClickListener!=null)
  105. mOnRightButtonClickListener.onClick(v);
  106. break;
  107. }
  108. }
  109. }

6、自定义底部工具栏,FragmentIndicator.java:

[java] view plain copy
  1. packagecom.eoe.tampletfragment.fragment;
  2. importandroid.content.Context;
  3. importandroid.graphics.Color;
  4. importandroid.util.AttributeSet;
  5. importandroid.util.TypedValue;
  6. importandroid.view.Gravity;
  7. importandroid.view.View;
  8. importandroid.view.View.OnClickListener;
  9. importandroid.widget.ImageView;
  10. importandroid.widget.LinearLayout;
  11. importandroid.widget.TextView;
  12. importcom.eoe.tampletfragment.R;

更多相关文章

  1. 【Android】第6章(1)对话框-- 本章示例主界面
  2. Android(安卓)使用SQLiteDatabase操作SQLite数据库(一)
  3. Android笔记之广播Broadcast
  4. uniapp原生插件开发之调用原生方法(android)
  5. 初识Android(安卓)回调机制
  6. android 如何使用LaunchMode
  7. android 笔记 --- 相机应用
  8. android多线程handler+runOnUithread+view.post+handler.post
  9. Android开发网上的一些重要知识点_2

随机推荐

  1. Android核心分析(14)------ Android(安卓)G
  2. [置顶] android adapter
  3. Apple IOS、Android、WebOS系统体系架构
  4. [Android] 无线adb调试
  5. 模拟器上安装Android(安卓)Market
  6. android中的资源访问
  7. Android(安卓)MVP 构架初试
  8. Android(安卓)源码分析-Dalvik 虚拟机创
  9. Google Android操作系统内核编译图文教程
  10. Android注解及反射实战--手写ButterKnife