zoukankan      html  css  js  c++  java
  • Android Fragment应用实战,使用碎片向ActivityGroup说再见

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/13171191

    现在Fragment的应用真的是越来越广泛了,之前Android在3.0版本加入Fragment的时候,主要是为了解决Android Pad屏幕比较大,空间不能充分利用的问题,但现在即使只是在手机上,也有很多的场景可以运用到Fragment了,今天我们就来学习其中一个特别棒的应用技巧。

    很多手机应用都会有一个非常类似的功能,即屏幕的下方显示一行Tab标签选项,点击不同的标签就可以切换到不同的界面,如以下几个应用所示:

    上面三个应用从左到右分别是QQ、新浪微博和支付宝钱包,可见,这种底部标签式的布局策略真的非常常见。

    那么话说回来,这种效果到底是如何的呢?熟悉Android的朋友一定都会知道,很简单嘛,使用TabHost就OK了!但是殊不知,TabHost并非是那么的简单,它的可扩展性非常的差,不能随意地定制Tab项显示的内容,而且运行还要依赖于ActivityGroup。ActivityGroup原本主要是用于为每一个TabHost的子项管理一个单独的Activity,但目前已经被废弃了。为什么呢?当然就是因为Fragment的出现了!查看Android官方文档中ActivityGroup的描述,如下所示:

    可以看到,在API 13的时候Android就已经将ActivityGroup废弃掉了,并且官方推荐的替代方式就是使用Fragment,因为它使用起来更加的灵活。那么剩下的问题就是如何借助Fragment来完成类似于TabHost一般的效果了,因此我们自然要动起手来了。

    在开始之前,首先你必须已经了解Fragment的用法了,如果你对Fragment还比较陌生的话,建议先去阅读我前面的一篇文章 Android Fragment完全解析,关于碎片你所需知道的一切

    另外,我们还应该准备好程序所需要的资源,比如说每一个Tab项中所用到的图片。我已经事先从QQ里截好了几张图作为这个项目的资源,稍后会连同源码一起给出。

    新建一个项目,起名就叫FragmentDemo,这里我使用的是4.0的API。

    下面开始编程工作,这里我们首先需要去编写一个类似于QQ的主界面,当然只会去编写界面最下方的TabHost部分,而不会编写上面的内容界面部分,因为内容界面是应该写在Fragment的布局里的。打开或新建activity_main.xml作为程序的主布局文件,在里面加入如下代码:

    1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    2. android:layout_width="match_parent"
    3. android:layout_height="match_parent"
    4. android:orientation="vertical" >
    5. <FrameLayout
    6. android:id="@+id/content"
    7. android:layout_width="match_parent"
    8. android:layout_height="0dp"
    9. android:layout_weight="1" >
    10. </FrameLayout>
    11. <LinearLayout
    12. android:layout_width="match_parent"
    13. android:layout_height="60dp"
    14. android:background="@drawable/tab_bg" >
    15. <RelativeLayout
    16. android:id="@+id/message_layout"
    17. android:layout_width="0dp"
    18. android:layout_height="match_parent"
    19. android:layout_weight="1" >
    20. <LinearLayout
    21. android:layout_width="match_parent"
    22. android:layout_height="wrap_content"
    23. android:layout_centerVertical="true"
    24. android:orientation="vertical" >
    25. <ImageView
    26. android:id="@+id/message_image"
    27. android:layout_width="wrap_content"
    28. android:layout_height="wrap_content"
    29. android:layout_gravity="center_horizontal"
    30. android:src="@drawable/message_unselected" />
    31. <TextView
    32. android:id="@+id/message_text"
    33. android:layout_width="wrap_content"
    34. android:layout_height="wrap_content"
    35. android:layout_gravity="center_horizontal"
    36. android:text="消息"
    37. android:textColor="#82858b" />
    38. </LinearLayout>
    39. </RelativeLayout>
    40. <RelativeLayout
    41. android:id="@+id/contacts_layout"
    42. android:layout_width="0dp"
    43. android:layout_height="match_parent"
    44. android:layout_weight="1" >
    45. <LinearLayout
    46. android:layout_width="match_parent"
    47. android:layout_height="wrap_content"
    48. android:layout_centerVertical="true"
    49. android:orientation="vertical" >
    50. <ImageView
    51. android:id="@+id/contacts_image"
    52. android:layout_width="wrap_content"
    53. android:layout_height="wrap_content"
    54. android:layout_gravity="center_horizontal"
    55. android:src="@drawable/contacts_unselected" />
    56. <TextView
    57. android:id="@+id/contacts_text"
    58. android:layout_width="wrap_content"
    59. android:layout_height="wrap_content"
    60. android:layout_gravity="center_horizontal"
    61. android:text="联系人"
    62. android:textColor="#82858b" />
    63. </LinearLayout>
    64. </RelativeLayout>
    65. <RelativeLayout
    66. android:id="@+id/news_layout"
    67. android:layout_width="0dp"
    68. android:layout_height="match_parent"
    69. android:layout_weight="1" >
    70. <LinearLayout
    71. android:layout_width="match_parent"
    72. android:layout_height="wrap_content"
    73. android:layout_centerVertical="true"
    74. android:orientation="vertical" >
    75. <ImageView
    76. android:id="@+id/news_image"
    77. android:layout_width="wrap_content"
    78. android:layout_height="wrap_content"
    79. android:layout_gravity="center_horizontal"
    80. android:src="@drawable/news_unselected" />
    81. <TextView
    82. android:id="@+id/news_text"
    83. android:layout_width="wrap_content"
    84. android:layout_height="wrap_content"
    85. android:layout_gravity="center_horizontal"
    86. android:text="动态"
    87. android:textColor="#82858b" />
    88. </LinearLayout>
    89. </RelativeLayout>
    90. <RelativeLayout
    91. android:id="@+id/setting_layout"
    92. android:layout_width="0dp"
    93. android:layout_height="match_parent"
    94. android:layout_weight="1" >
    95. <LinearLayout
    96. android:layout_width="match_parent"
    97. android:layout_height="wrap_content"
    98. android:layout_centerVertical="true"
    99. android:orientation="vertical" >
    100. <ImageView
    101. android:id="@+id/setting_image"
    102. android:layout_width="wrap_content"
    103. android:layout_height="wrap_content"
    104. android:layout_gravity="center_horizontal"
    105. android:src="@drawable/setting_unselected" />
    106. <TextView
    107. android:id="@+id/setting_text"
    108. android:layout_width="wrap_content"
    109. android:layout_height="wrap_content"
    110. android:layout_gravity="center_horizontal"
    111. android:text="设置"
    112. android:textColor="#82858b" />
    113. </LinearLayout>
    114. </RelativeLayout>
    115. </LinearLayout>
    116. </LinearLayout>
    1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    2.     android:layout_width="match_parent"  
    3.     android:layout_height="match_parent"  
    4.     android:orientation="vertical" >  
    5.   
    6.     <FrameLayout  
    7.         android:id="@+id/content"  
    8.         android:layout_width="match_parent"  
    9.         android:layout_height="0dp"  
    10.         android:layout_weight="1" >  
    11.     </FrameLayout>  
    12.   
    13.     <LinearLayout  
    14.         android:layout_width="match_parent"  
    15.         android:layout_height="60dp"  
    16.         android:background="@drawable/tab_bg" >  
    17.   
    18.         <RelativeLayout  
    19.             android:id="@+id/message_layout"  
    20.             android:layout_width="0dp"  
    21.             android:layout_height="match_parent"  
    22.             android:layout_weight="1" >  
    23.   
    24.             <LinearLayout  
    25.                 android:layout_width="match_parent"  
    26.                 android:layout_height="wrap_content"  
    27.                 android:layout_centerVertical="true"  
    28.                 android:orientation="vertical" >  
    29.   
    30.                 <ImageView  
    31.                     android:id="@+id/message_image"  
    32.                     android:layout_width="wrap_content"  
    33.                     android:layout_height="wrap_content"  
    34.                     android:layout_gravity="center_horizontal"  
    35.                     android:src="@drawable/message_unselected" />  
    36.   
    37.                 <TextView  
    38.                     android:id="@+id/message_text"  
    39.                     android:layout_width="wrap_content"  
    40.                     android:layout_height="wrap_content"  
    41.                     android:layout_gravity="center_horizontal"  
    42.                     android:text="消息"  
    43.                     android:textColor="#82858b" />  
    44.             </LinearLayout>  
    45.         </RelativeLayout>  
    46.   
    47.         <RelativeLayout  
    48.             android:id="@+id/contacts_layout"  
    49.             android:layout_width="0dp"  
    50.             android:layout_height="match_parent"  
    51.             android:layout_weight="1" >  
    52.   
    53.             <LinearLayout  
    54.                 android:layout_width="match_parent"  
    55.                 android:layout_height="wrap_content"  
    56.                 android:layout_centerVertical="true"  
    57.                 android:orientation="vertical" >  
    58.   
    59.                 <ImageView  
    60.                     android:id="@+id/contacts_image"  
    61.                     android:layout_width="wrap_content"  
    62.                     android:layout_height="wrap_content"  
    63.                     android:layout_gravity="center_horizontal"  
    64.                     android:src="@drawable/contacts_unselected" />  
    65.   
    66.                 <TextView  
    67.                     android:id="@+id/contacts_text"  
    68.                     android:layout_width="wrap_content"  
    69.                     android:layout_height="wrap_content"  
    70.                     android:layout_gravity="center_horizontal"  
    71.                     android:text="联系人"  
    72.                     android:textColor="#82858b" />  
    73.             </LinearLayout>  
    74.         </RelativeLayout>  
    75.   
    76.         <RelativeLayout  
    77.             android:id="@+id/news_layout"  
    78.             android:layout_width="0dp"  
    79.             android:layout_height="match_parent"  
    80.             android:layout_weight="1" >  
    81.   
    82.             <LinearLayout  
    83.                 android:layout_width="match_parent"  
    84.                 android:layout_height="wrap_content"  
    85.                 android:layout_centerVertical="true"  
    86.                 android:orientation="vertical" >  
    87.   
    88.                 <ImageView  
    89.                     android:id="@+id/news_image"  
    90.                     android:layout_width="wrap_content"  
    91.                     android:layout_height="wrap_content"  
    92.                     android:layout_gravity="center_horizontal"  
    93.                     android:src="@drawable/news_unselected" />  
    94.   
    95.                 <TextView  
    96.                     android:id="@+id/news_text"  
    97.                     android:layout_width="wrap_content"  
    98.                     android:layout_height="wrap_content"  
    99.                     android:layout_gravity="center_horizontal"  
    100.                     android:text="动态"  
    101.                     android:textColor="#82858b" />  
    102.             </LinearLayout>  
    103.         </RelativeLayout>  
    104.   
    105.         <RelativeLayout  
    106.             android:id="@+id/setting_layout"  
    107.             android:layout_width="0dp"  
    108.             android:layout_height="match_parent"  
    109.             android:layout_weight="1" >  
    110.   
    111.             <LinearLayout  
    112.                 android:layout_width="match_parent"  
    113.                 android:layout_height="wrap_content"  
    114.                 android:layout_centerVertical="true"  
    115.                 android:orientation="vertical" >  
    116.   
    117.                 <ImageView  
    118.                     android:id="@+id/setting_image"  
    119.                     android:layout_width="wrap_content"  
    120.                     android:layout_height="wrap_content"  
    121.                     android:layout_gravity="center_horizontal"  
    122.                     android:src="@drawable/setting_unselected" />  
    123.   
    124.                 <TextView  
    125.                     android:id="@+id/setting_text"  
    126.                     android:layout_width="wrap_content"  
    127.                     android:layout_height="wrap_content"  
    128.                     android:layout_gravity="center_horizontal"  
    129.                     android:text="设置"  
    130.                     android:textColor="#82858b" />  
    131.             </LinearLayout>  
    132.         </RelativeLayout>  
    133.     </LinearLayout>  
    134.   
    135. </LinearLayout>  
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    
        <FrameLayout
            android:id="@+id/content"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" >
        </FrameLayout>
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:background="@drawable/tab_bg" >
    
            <RelativeLayout
                android:id="@+id/message_layout"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1" >
    
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_centerVertical="true"
                    android:orientation="vertical" >
    
                    <ImageView
                        android:id="@+id/message_image"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:src="@drawable/message_unselected" />
    
                    <TextView
                        android:id="@+id/message_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:text="消息"
                        android:textColor="#82858b" />
                </LinearLayout>
            </RelativeLayout>
    
            <RelativeLayout
                android:id="@+id/contacts_layout"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1" >
    
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_centerVertical="true"
                    android:orientation="vertical" >
    
                    <ImageView
                        android:id="@+id/contacts_image"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:src="@drawable/contacts_unselected" />
    
                    <TextView
                        android:id="@+id/contacts_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:text="联系人"
                        android:textColor="#82858b" />
                </LinearLayout>
            </RelativeLayout>
    
            <RelativeLayout
                android:id="@+id/news_layout"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1" >
    
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_centerVertical="true"
                    android:orientation="vertical" >
    
                    <ImageView
                        android:id="@+id/news_image"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:src="@drawable/news_unselected" />
    
                    <TextView
                        android:id="@+id/news_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:text="动态"
                        android:textColor="#82858b" />
                </LinearLayout>
            </RelativeLayout>
    
            <RelativeLayout
                android:id="@+id/setting_layout"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1" >
    
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_centerVertical="true"
                    android:orientation="vertical" >
    
                    <ImageView
                        android:id="@+id/setting_image"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:src="@drawable/setting_unselected" />
    
                    <TextView
                        android:id="@+id/setting_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:text="设置"
                        android:textColor="#82858b" />
                </LinearLayout>
            </RelativeLayout>
        </LinearLayout>
    
    </LinearLayout>

    这段布局代码虽然有点长,但其实主要就分为两部分。第一个部分就是FrameLayout,这里只是给FrameLayout的id设置成content,并没有在里面添加任何具体的内容,因为具体的内容是要在后面动态进行添加的。第二个部分就是FrameLayout下面的LinearLayout,这个LinearLayout中包含的就是整个类似于TabHost的布局。可以看到,我们将这个LinearLayout又等分成了四份,每一份中都会显示一个ImageView和一个TextView。ImageView用于显示当前Tab的图标,TextView用于显示当前Tab的标题,这个效果就会和QQ非常得类似。

    既然是等分成了四分,那接下来我们自然要去分别实现四个Fragment和它们的布局了。新建一个message_layout.xml作为消息界面的布局,代码如下所示:

    1. <?xml version="1.0" encoding="utf-8"?>
    2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3. android:layout_width="match_parent"
    4. android:layout_height="match_parent" >
    5. <LinearLayout
    6. android:layout_width="wrap_content"
    7. android:layout_height="wrap_content"
    8. android:layout_centerInParent="true"
    9. android:orientation="vertical" >
    10. <ImageView
    11. android:layout_width="wrap_content"
    12. android:layout_height="wrap_content"
    13. android:layout_gravity="center_horizontal"
    14. android:src="@drawable/message_selected" />
    15. <TextView
    16. android:layout_width="wrap_content"
    17. android:layout_height="wrap_content"
    18. android:layout_gravity="center_horizontal"
    19. android:padding="10dp"
    20. android:text="这是消息界面"
    21. android:textSize="20sp" />
    22. </LinearLayout>
    23. </RelativeLayout>
    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.   
    6.     <LinearLayout  
    7.         android:layout_width="wrap_content"  
    8.         android:layout_height="wrap_content"  
    9.         android:layout_centerInParent="true"  
    10.         android:orientation="vertical" >  
    11.   
    12.         <ImageView  
    13.             android:layout_width="wrap_content"  
    14.             android:layout_height="wrap_content"  
    15.             android:layout_gravity="center_horizontal"  
    16.             android:src="@drawable/message_selected" />  
    17.   
    18.         <TextView  
    19.             android:layout_width="wrap_content"  
    20.             android:layout_height="wrap_content"  
    21.             android:layout_gravity="center_horizontal"  
    22.             android:padding="10dp"  
    23.             android:text="这是消息界面"  
    24.             android:textSize="20sp" />  
    25.     </LinearLayout>  
    26.   
    27. </RelativeLayout>  
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:orientation="vertical" >
    
            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:src="@drawable/message_selected" />
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:padding="10dp"
                android:text="这是消息界面"
                android:textSize="20sp" />
        </LinearLayout>
    
    </RelativeLayout>

    这个布局就相对简单多了,只是在屏幕的正中央显示一个消息图标,以及一段文字。

    然后要去创建对应这个布局的Fragment。新建MessageFragment继承自Fragment,代码如下所示:

    1. public class MessageFragment extends Fragment {
    2. public View onCreateView(LayoutInflater inflater, ViewGroup container,
    3. Bundle savedInstanceState) {
    4. View messageLayout = inflater.inflate(R.layout.message_layout, container, false);
    5. return messageLayout;
    6. }
    7. }
    1. public class MessageFragment extends Fragment {  
    2.   
    3.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
    4.             Bundle savedInstanceState) {  
    5.         View messageLayout = inflater.inflate(R.layout.message_layout, container, false);  
    6.         return messageLayout;  
    7.     }  
    8.   
    9. }  
    public class MessageFragment extends Fragment {
    
    	public View onCreateView(LayoutInflater inflater, ViewGroup container,
    			Bundle savedInstanceState) {
    		View messageLayout = inflater.inflate(R.layout.message_layout, container, false);
    		return messageLayout;
    	}
    
    }

    后面就是依葫芦画瓢,把其它几个Fragment以及对应的布局创建出来。新建contacts_layout.xml作为联系人界面的布局,代码如下所示:

    1. <?xml version="1.0" encoding="utf-8"?>
    2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3. android:layout_width="match_parent"
    4. android:layout_height="match_parent" >
    5. <LinearLayout
    6. android:layout_width="wrap_content"
    7. android:layout_height="wrap_content"
    8. android:layout_centerInParent="true"
    9. android:orientation="vertical" >
    10. <ImageView
    11. android:layout_width="wrap_content"
    12. android:layout_height="wrap_content"
    13. android:layout_gravity="center_horizontal"
    14. android:src="@drawable/contacts_selected" />
    15. <TextView
    16. android:layout_width="wrap_content"
    17. android:layout_height="wrap_content"
    18. android:layout_gravity="center_horizontal"
    19. android:padding="10dp"
    20. android:text="这是联系人界面"
    21. android:textSize="20sp" />
    22. </LinearLayout>
    23. </RelativeLayout>
    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.   
    6.     <LinearLayout  
    7.         android:layout_width="wrap_content"  
    8.         android:layout_height="wrap_content"  
    9.         android:layout_centerInParent="true"  
    10.         android:orientation="vertical" >  
    11.   
    12.         <ImageView  
    13.             android:layout_width="wrap_content"  
    14.             android:layout_height="wrap_content"  
    15.             android:layout_gravity="center_horizontal"  
    16.             android:src="@drawable/contacts_selected" />  
    17.   
    18.         <TextView  
    19.             android:layout_width="wrap_content"  
    20.             android:layout_height="wrap_content"  
    21.             android:layout_gravity="center_horizontal"  
    22.             android:padding="10dp"  
    23.             android:text="这是联系人界面"  
    24.             android:textSize="20sp" />  
    25.     </LinearLayout>  
    26.   
    27. </RelativeLayout>  
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:orientation="vertical" >
    
            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:src="@drawable/contacts_selected" />
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:padding="10dp"
                android:text="这是联系人界面"
                android:textSize="20sp" />
        </LinearLayout>
    
    </RelativeLayout>

    再新建ContactsFragment继承自Fragment,代码如下所示:

    1. public class ContactsFragment extends Fragment {
    2. @Override
    3. public View onCreateView(LayoutInflater inflater, ViewGroup container,
    4. Bundle savedInstanceState) {
    5. View contactsLayout = inflater.inflate(R.layout.contacts_layout,
    6. container, false);
    7. return contactsLayout;
    8. }
    9. }
    1. public class ContactsFragment extends Fragment {  
    2.   
    3.     @Override  
    4.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
    5.             Bundle savedInstanceState) {  
    6.         View contactsLayout = inflater.inflate(R.layout.contacts_layout,  
    7.                 container, false);  
    8.         return contactsLayout;  
    9.     }  
    10.   
    11. }  
    public class ContactsFragment extends Fragment {
    
    	@Override
    	public View onCreateView(LayoutInflater inflater, ViewGroup container,
    			Bundle savedInstanceState) {
    		View contactsLayout = inflater.inflate(R.layout.contacts_layout,
    				container, false);
    		return contactsLayout;
    	}
    
    }

    然后新建news_layout.xml作为动态界面的布局,代码如下所示:

    1. <?xml version="1.0" encoding="utf-8"?>
    2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3. android:layout_width="match_parent"
    4. android:layout_height="match_parent" >
    5. <LinearLayout
    6. android:layout_width="wrap_content"
    7. android:layout_height="wrap_content"
    8. android:layout_centerInParent="true"
    9. android:orientation="vertical" >
    10. <ImageView
    11. android:layout_width="wrap_content"
    12. android:layout_height="wrap_content"
    13. android:layout_gravity="center_horizontal"
    14. android:src="@drawable/news_selected" />
    15. <TextView
    16. android:layout_width="wrap_content"
    17. android:layout_height="wrap_content"
    18. android:layout_gravity="center_horizontal"
    19. android:padding="10dp"
    20. android:text="这是动态界面"
    21. android:textSize="20sp" />
    22. </LinearLayout>
    23. </RelativeLayout>
    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.   
    6.     <LinearLayout  
    7.         android:layout_width="wrap_content"  
    8.         android:layout_height="wrap_content"  
    9.         android:layout_centerInParent="true"  
    10.         android:orientation="vertical" >  
    11.   
    12.         <ImageView  
    13.             android:layout_width="wrap_content"  
    14.             android:layout_height="wrap_content"  
    15.             android:layout_gravity="center_horizontal"  
    16.             android:src="@drawable/news_selected" />  
    17.   
    18.         <TextView  
    19.             android:layout_width="wrap_content"  
    20.             android:layout_height="wrap_content"  
    21.             android:layout_gravity="center_horizontal"  
    22.             android:padding="10dp"  
    23.             android:text="这是动态界面"  
    24.             android:textSize="20sp" />  
    25.     </LinearLayout>  
    26.   
    27. </RelativeLayout>  
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:orientation="vertical" >
    
            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:src="@drawable/news_selected" />
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:padding="10dp"
                android:text="这是动态界面"
                android:textSize="20sp" />
        </LinearLayout>
    
    </RelativeLayout>

    再新建NewsFragment继承自Fragment,代码如下所示:

    1. public class NewsFragment extends Fragment {
    2. @Override
    3. public View onCreateView(LayoutInflater inflater, ViewGroup container,
    4. Bundle savedInstanceState) {
    5. View newsLayout = inflater.inflate(R.layout.news_layout, container,
    6. false);
    7. return newsLayout;
    8. }
    9. }
    1. public class NewsFragment extends Fragment {  
    2.   
    3.     @Override  
    4.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
    5.             Bundle savedInstanceState) {  
    6.         View newsLayout = inflater.inflate(R.layout.news_layout, container,  
    7.                 false);  
    8.         return newsLayout;  
    9.     }  
    10.   
    11. }  
    public class NewsFragment extends Fragment {
    
    	@Override
    	public View onCreateView(LayoutInflater inflater, ViewGroup container,
    			Bundle savedInstanceState) {
    		View newsLayout = inflater.inflate(R.layout.news_layout, container,
    				false);
    		return newsLayout;
    	}
    
    }
    

    最后新建setting_layout.xml作为设置界面的布局,代码如下所示:

    1. <?xml version="1.0" encoding="utf-8"?>
    2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3. android:layout_width="match_parent"
    4. android:layout_height="match_parent" >
    5. <LinearLayout
    6. android:layout_width="wrap_content"
    7. android:layout_height="wrap_content"
    8. android:layout_centerInParent="true"
    9. android:orientation="vertical" >
    10. <ImageView
    11. android:layout_width="wrap_content"
    12. android:layout_height="wrap_content"
    13. android:layout_gravity="center_horizontal"
    14. android:src="@drawable/setting_selected" />
    15. <TextView
    16. android:layout_width="wrap_content"
    17. android:layout_height="wrap_content"
    18. android:layout_gravity="center_horizontal"
    19. android:padding="10dp"
    20. android:text="这是设置界面"
    21. android:textSize="20sp" />
    22. </LinearLayout>
    23. </RelativeLayout>
    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.   
    6.     <LinearLayout  
    7.         android:layout_width="wrap_content"  
    8.         android:layout_height="wrap_content"  
    9.         android:layout_centerInParent="true"  
    10.         android:orientation="vertical" >  
    11.   
    12.         <ImageView  
    13.             android:layout_width="wrap_content"  
    14.             android:layout_height="wrap_content"  
    15.             android:layout_gravity="center_horizontal"  
    16.             android:src="@drawable/setting_selected" />  
    17.   
    18.         <TextView  
    19.             android:layout_width="wrap_content"  
    20.             android:layout_height="wrap_content"  
    21.             android:layout_gravity="center_horizontal"  
    22.             android:padding="10dp"  
    23.             android:text="这是设置界面"  
    24.             android:textSize="20sp" />  
    25.     </LinearLayout>  
    26.   
    27. </RelativeLayout>  
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:orientation="vertical" >
    
            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:src="@drawable/setting_selected" />
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:padding="10dp"
                android:text="这是设置界面"
                android:textSize="20sp" />
        </LinearLayout>
    
    </RelativeLayout>

    再新建SettingFragment继承自Fragment,代码如下所示:

    1. public class SettingFragment extends Fragment {
    2. @Override
    3. public View onCreateView(LayoutInflater inflater, ViewGroup container,
    4. Bundle savedInstanceState) {
    5. View settingLayout = inflater.inflate(R.layout.setting_layout,
    6. container, false);
    7. return settingLayout;
    8. }
    9. }
    1. public class SettingFragment extends Fragment {  
    2.   
    3.     @Override  
    4.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
    5.             Bundle savedInstanceState) {  
    6.         View settingLayout = inflater.inflate(R.layout.setting_layout,  
    7.                 container, false);  
    8.         return settingLayout;  
    9.     }  
    10.   
    11. }  
    public class SettingFragment extends Fragment {
    
    	@Override
    	public View onCreateView(LayoutInflater inflater, ViewGroup container,
    			Bundle savedInstanceState) {
    		View settingLayout = inflater.inflate(R.layout.setting_layout,
    				container, false);
    		return settingLayout;
    	}
    
    }

    这样我们就把每一个Fragment,以及它们所对应的布局文件都创建好了。接下来也就是最关键的步骤了,打开或新建MainActivity作为主Activity,代码如下所示:

    1. /**
    2. * 项目的主Activity,所有的Fragment都嵌入在这里。
    3. *
    4. * @author guolin
    5. */
    6. public class MainActivity extends Activity implements OnClickListener {
    7. /**
    8. * 用于展示消息的Fragment
    9. */
    10. private MessageFragment messageFragment;
    11. /**
    12. * 用于展示联系人的Fragment
    13. */
    14. private ContactsFragment contactsFragment;
    15. /**
    16. * 用于展示动态的Fragment
    17. */
    18. private NewsFragment newsFragment;
    19. /**
    20. * 用于展示设置的Fragment
    21. */
    22. private SettingFragment settingFragment;
    23. /**
    24. * 消息界面布局
    25. */
    26. private View messageLayout;
    27. /**
    28. * 联系人界面布局
    29. */
    30. private View contactsLayout;
    31. /**
    32. * 动态界面布局
    33. */
    34. private View newsLayout;
    35. /**
    36. * 设置界面布局
    37. */
    38. private View settingLayout;
    39. /**
    40. * 在Tab布局上显示消息图标的控件
    41. */
    42. private ImageView messageImage;
    43. /**
    44. * 在Tab布局上显示联系人图标的控件
    45. */
    46. private ImageView contactsImage;
    47. /**
    48. * 在Tab布局上显示动态图标的控件
    49. */
    50. private ImageView newsImage;
    51. /**
    52. * 在Tab布局上显示设置图标的控件
    53. */
    54. private ImageView settingImage;
    55. /**
    56. * 在Tab布局上显示消息标题的控件
    57. */
    58. private TextView messageText;
    59. /**
    60. * 在Tab布局上显示联系人标题的控件
    61. */
    62. private TextView contactsText;
    63. /**
    64. * 在Tab布局上显示动态标题的控件
    65. */
    66. private TextView newsText;
    67. /**
    68. * 在Tab布局上显示设置标题的控件
    69. */
    70. private TextView settingText;
    71. /**
    72. * 用于对Fragment进行管理
    73. */
    74. private FragmentManager fragmentManager;
    75. @Override
    76. protected void onCreate(Bundle savedInstanceState) {
    77. super.onCreate(savedInstanceState);
    78. requestWindowFeature(Window.FEATURE_NO_TITLE);
    79. setContentView(R.layout.activity_main);
    80. // 初始化布局元素
    81. initViews();
    82. fragmentManager = getFragmentManager();
    83. // 第一次启动时选中第0个tab
    84. setTabSelection(0);
    85. }
    86. /**
    87. * 在这里获取到每个需要用到的控件的实例,并给它们设置好必要的点击事件。
    88. */
    89. private void initViews() {
    90. messageLayout = findViewById(R.id.message_layout);
    91. contactsLayout = findViewById(R.id.contacts_layout);
    92. newsLayout = findViewById(R.id.news_layout);
    93. settingLayout = findViewById(R.id.setting_layout);
    94. messageImage = (ImageView) findViewById(R.id.message_image);
    95. contactsImage = (ImageView) findViewById(R.id.contacts_image);
    96. newsImage = (ImageView) findViewById(R.id.news_image);
    97. settingImage = (ImageView) findViewById(R.id.setting_image);
    98. messageText = (TextView) findViewById(R.id.message_text);
    99. contactsText = (TextView) findViewById(R.id.contacts_text);
    100. newsText = (TextView) findViewById(R.id.news_text);
    101. settingText = (TextView) findViewById(R.id.setting_text);
    102. messageLayout.setOnClickListener(this);
    103. contactsLayout.setOnClickListener(this);
    104. newsLayout.setOnClickListener(this);
    105. settingLayout.setOnClickListener(this);
    106. }
    107. @Override
    108. public void onClick(View v) {
    109. switch (v.getId()) {
    110. case R.id.message_layout:
    111. // 当点击了消息tab时,选中第1个tab
    112. setTabSelection(0);
    113. break;
    114. case R.id.contacts_layout:
    115. // 当点击了联系人tab时,选中第2个tab
    116. setTabSelection(1);
    117. break;
    118. case R.id.news_layout:
    119. // 当点击了动态tab时,选中第3个tab
    120. setTabSelection(2);
    121. break;
    122. case R.id.setting_layout:
    123. // 当点击了设置tab时,选中第4个tab
    124. setTabSelection(3);
    125. break;
    126. default:
    127. break;
    128. }
    129. }
    130. /**
    131. * 根据传入的index参数来设置选中的tab页。
    132. *
    133. * @param index
    134. * 每个tab页对应的下标。0表示消息,1表示联系人,2表示动态,3表示设置。
    135. */
    136. private void setTabSelection(int index) {
    137. // 每次选中之前先清楚掉上次的选中状态
    138. clearSelection();
    139. // 开启一个Fragment事务
    140. FragmentTransaction transaction = fragmentManager.beginTransaction();
    141. // 先隐藏掉所有的Fragment,以防止有多个Fragment显示在界面上的情况
    142. hideFragments(transaction);
    143. switch (index) {
    144. case 0:
    145. // 当点击了消息tab时,改变控件的图片和文字颜色
    146. messageImage.setImageResource(R.drawable.message_selected);
    147. messageText.setTextColor(Color.WHITE);
    148. if (messageFragment == null) {
    149. // 如果MessageFragment为空,则创建一个并添加到界面上
    150. messageFragment = new MessageFragment();
    151. transaction.add(R.id.content, messageFragment);
    152. } else {
    153. // 如果MessageFragment不为空,则直接将它显示出来
    154. transaction.show(messageFragment);
    155. }
    156. break;
    157. case 1:
    158. // 当点击了联系人tab时,改变控件的图片和文字颜色
    159. contactsImage.setImageResource(R.drawable.contacts_selected);
    160. contactsText.setTextColor(Color.WHITE);
    161. if (contactsFragment == null) {
    162. // 如果ContactsFragment为空,则创建一个并添加到界面上
    163. contactsFragment = new ContactsFragment();
    164. transaction.add(R.id.content, contactsFragment);
    165. } else {
    166. // 如果ContactsFragment不为空,则直接将它显示出来
    167. transaction.show(contactsFragment);
    168. }
    169. break;
    170. case 2:
    171. // 当点击了动态tab时,改变控件的图片和文字颜色
    172. newsImage.setImageResource(R.drawable.news_selected);
    173. newsText.setTextColor(Color.WHITE);
    174. if (newsFragment == null) {
    175. // 如果NewsFragment为空,则创建一个并添加到界面上
    176. newsFragment = new NewsFragment();
    177. transaction.add(R.id.content, newsFragment);
    178. } else {
    179. // 如果NewsFragment不为空,则直接将它显示出来
    180. transaction.show(newsFragment);
    181. }
    182. break;
    183. case 3:
    184. default:
    185. // 当点击了设置tab时,改变控件的图片和文字颜色
    186. settingImage.setImageResource(R.drawable.setting_selected);
    187. settingText.setTextColor(Color.WHITE);
    188. if (settingFragment == null) {
    189. // 如果SettingFragment为空,则创建一个并添加到界面上
    190. settingFragment = new SettingFragment();
    191. transaction.add(R.id.content, settingFragment);
    192. } else {
    193. // 如果SettingFragment不为空,则直接将它显示出来
    194. transaction.show(settingFragment);
    195. }
    196. break;
    197. }
    198. transaction.commit();
    199. }
    200. /**
    201. * 清除掉所有的选中状态。
    202. */
    203. private void clearSelection() {
    204. messageImage.setImageResource(R.drawable.message_unselected);
    205. messageText.setTextColor(Color.parseColor("#82858b"));
    206. contactsImage.setImageResource(R.drawable.contacts_unselected);
    207. contactsText.setTextColor(Color.parseColor("#82858b"));
    208. newsImage.setImageResource(R.drawable.news_unselected);
    209. newsText.setTextColor(Color.parseColor("#82858b"));
    210. settingImage.setImageResource(R.drawable.setting_unselected);
    211. settingText.setTextColor(Color.parseColor("#82858b"));
    212. }
    213. /**
    214. * 将所有的Fragment都置为隐藏状态。
    215. *
    216. * @param transaction
    217. * 用于对Fragment执行操作的事务
    218. */
    219. private void hideFragments(FragmentTransaction transaction) {
    220. if (messageFragment != null) {
    221. transaction.hide(messageFragment);
    222. }
    223. if (contactsFragment != null) {
    224. transaction.hide(contactsFragment);
    225. }
    226. if (newsFragment != null) {
    227. transaction.hide(newsFragment);
    228. }
    229. if (settingFragment != null) {
    230. transaction.hide(settingFragment);
    231. }
    232. }
    233. }
    1. /** 
    2.  * 项目的主Activity,所有的Fragment都嵌入在这里。 
    3.  *  
    4.  * @author guolin 
    5.  */  
    6. public class MainActivity extends Activity implements OnClickListener {  
    7.   
    8.     /** 
    9.      * 用于展示消息的Fragment 
    10.      */  
    11.     private MessageFragment messageFragment;  
    12.   
    13.     /** 
    14.      * 用于展示联系人的Fragment 
    15.      */  
    16.     private ContactsFragment contactsFragment;  
    17.   
    18.     /** 
    19.      * 用于展示动态的Fragment 
    20.      */  
    21.     private NewsFragment newsFragment;  
    22.   
    23.     /** 
    24.      * 用于展示设置的Fragment 
    25.      */  
    26.     private SettingFragment settingFragment;  
    27.   
    28.     /** 
    29.      * 消息界面布局 
    30.      */  
    31.     private View messageLayout;  
    32.   
    33.     /** 
    34.      * 联系人界面布局 
    35.      */  
    36.     private View contactsLayout;  
    37.   
    38.     /** 
    39.      * 动态界面布局 
    40.      */  
    41.     private View newsLayout;  
    42.   
    43.     /** 
    44.      * 设置界面布局 
    45.      */  
    46.     private View settingLayout;  
    47.   
    48.     /** 
    49.      * 在Tab布局上显示消息图标的控件 
    50.      */  
    51.     private ImageView messageImage;  
    52.   
    53.     /** 
    54.      * 在Tab布局上显示联系人图标的控件 
    55.      */  
    56.     private ImageView contactsImage;  
    57.   
    58.     /** 
    59.      * 在Tab布局上显示动态图标的控件 
    60.      */  
    61.     private ImageView newsImage;  
    62.   
    63.     /** 
    64.      * 在Tab布局上显示设置图标的控件 
    65.      */  
    66.     private ImageView settingImage;  
    67.   
    68.     /** 
    69.      * 在Tab布局上显示消息标题的控件 
    70.      */  
    71.     private TextView messageText;  
    72.   
    73.     /** 
    74.      * 在Tab布局上显示联系人标题的控件 
    75.      */  
    76.     private TextView contactsText;  
    77.   
    78.     /** 
    79.      * 在Tab布局上显示动态标题的控件 
    80.      */  
    81.     private TextView newsText;  
    82.   
    83.     /** 
    84.      * 在Tab布局上显示设置标题的控件 
    85.      */  
    86.     private TextView settingText;  
    87.   
    88.     /** 
    89.      * 用于对Fragment进行管理 
    90.      */  
    91.     private FragmentManager fragmentManager;  
    92.   
    93.     @Override  
    94.     protected void onCreate(Bundle savedInstanceState) {  
    95.         super.onCreate(savedInstanceState);  
    96.         requestWindowFeature(Window.FEATURE_NO_TITLE);  
    97.         setContentView(R.layout.activity_main);  
    98.         // 初始化布局元素  
    99.         initViews();  
    100.         fragmentManager = getFragmentManager();  
    101.         // 第一次启动时选中第0个tab  
    102.         setTabSelection(0);  
    103.     }  
    104.   
    105.     /** 
    106.      * 在这里获取到每个需要用到的控件的实例,并给它们设置好必要的点击事件。 
    107.      */  
    108.     private void initViews() {  
    109.         messageLayout = findViewById(R.id.message_layout);  
    110.         contactsLayout = findViewById(R.id.contacts_layout);  
    111.         newsLayout = findViewById(R.id.news_layout);  
    112.         settingLayout = findViewById(R.id.setting_layout);  
    113.         messageImage = (ImageView) findViewById(R.id.message_image);  
    114.         contactsImage = (ImageView) findViewById(R.id.contacts_image);  
    115.         newsImage = (ImageView) findViewById(R.id.news_image);  
    116.         settingImage = (ImageView) findViewById(R.id.setting_image);  
    117.         messageText = (TextView) findViewById(R.id.message_text);  
    118.         contactsText = (TextView) findViewById(R.id.contacts_text);  
    119.         newsText = (TextView) findViewById(R.id.news_text);  
    120.         settingText = (TextView) findViewById(R.id.setting_text);  
    121.         messageLayout.setOnClickListener(this);  
    122.         contactsLayout.setOnClickListener(this);  
    123.         newsLayout.setOnClickListener(this);  
    124.         settingLayout.setOnClickListener(this);  
    125.     }  
    126.   
    127.     @Override  
    128.     public void onClick(View v) {  
    129.         switch (v.getId()) {  
    130.         case R.id.message_layout:  
    131.             // 当点击了消息tab时,选中第1个tab  
    132.             setTabSelection(0);  
    133.             break;  
    134.         case R.id.contacts_layout:  
    135.             // 当点击了联系人tab时,选中第2个tab  
    136.             setTabSelection(1);  
    137.             break;  
    138.         case R.id.news_layout:  
    139.             // 当点击了动态tab时,选中第3个tab  
    140.             setTabSelection(2);  
    141.             break;  
    142.         case R.id.setting_layout:  
    143.             // 当点击了设置tab时,选中第4个tab  
    144.             setTabSelection(3);  
    145.             break;  
    146.         default:  
    147.             break;  
    148.         }  
    149.     }  
    150.   
    151.     /** 
    152.      * 根据传入的index参数来设置选中的tab页。 
    153.      *  
    154.      * @param index 
    155.      *            每个tab页对应的下标。0表示消息,1表示联系人,2表示动态,3表示设置。 
    156.      */  
    157.     private void setTabSelection(int index) {  
    158.         // 每次选中之前先清楚掉上次的选中状态  
    159.         clearSelection();  
    160.         // 开启一个Fragment事务  
    161.         FragmentTransaction transaction = fragmentManager.beginTransaction();  
    162.         // 先隐藏掉所有的Fragment,以防止有多个Fragment显示在界面上的情况  
    163.         hideFragments(transaction);  
    164.         switch (index) {  
    165.         case 0:  
    166.             // 当点击了消息tab时,改变控件的图片和文字颜色  
    167.             messageImage.setImageResource(R.drawable.message_selected);  
    168.             messageText.setTextColor(Color.WHITE);  
    169.             if (messageFragment == null) {  
    170.                 // 如果MessageFragment为空,则创建一个并添加到界面上  
    171.                 messageFragment = new MessageFragment();  
    172.                 transaction.add(R.id.content, messageFragment);  
    173.             } else {  
    174.                 // 如果MessageFragment不为空,则直接将它显示出来  
    175.                 transaction.show(messageFragment);  
    176.             }  
    177.             break;  
    178.         case 1:  
    179.             // 当点击了联系人tab时,改变控件的图片和文字颜色  
    180.             contactsImage.setImageResource(R.drawable.contacts_selected);  
    181.             contactsText.setTextColor(Color.WHITE);  
    182.             if (contactsFragment == null) {  
    183.                 // 如果ContactsFragment为空,则创建一个并添加到界面上  
    184.                 contactsFragment = new ContactsFragment();  
    185.                 transaction.add(R.id.content, contactsFragment);  
    186.             } else {  
    187.                 // 如果ContactsFragment不为空,则直接将它显示出来  
    188.                 transaction.show(contactsFragment);  
    189.             }  
    190.             break;  
    191.         case 2:  
    192.             // 当点击了动态tab时,改变控件的图片和文字颜色  
    193.             newsImage.setImageResource(R.drawable.news_selected);  
    194.             newsText.setTextColor(Color.WHITE);  
    195.             if (newsFragment == null) {  
    196.                 // 如果NewsFragment为空,则创建一个并添加到界面上  
    197.                 newsFragment = new NewsFragment();  
    198.                 transaction.add(R.id.content, newsFragment);  
    199.             } else {  
    200.                 // 如果NewsFragment不为空,则直接将它显示出来  
    201.                 transaction.show(newsFragment);  
    202.             }  
    203.             break;  
    204.         case 3:  
    205.         default:  
    206.             // 当点击了设置tab时,改变控件的图片和文字颜色  
    207.             settingImage.setImageResource(R.drawable.setting_selected);  
    208.             settingText.setTextColor(Color.WHITE);  
    209.             if (settingFragment == null) {  
    210.                 // 如果SettingFragment为空,则创建一个并添加到界面上  
    211.                 settingFragment = new SettingFragment();  
    212.                 transaction.add(R.id.content, settingFragment);  
    213.             } else {  
    214.                 // 如果SettingFragment不为空,则直接将它显示出来  
    215.                 transaction.show(settingFragment);  
    216.             }  
    217.             break;  
    218.         }  
    219.         transaction.commit();  
    220.     }  
    221.   
    222.     /** 
    223.      * 清除掉所有的选中状态。 
    224.      */  
    225.     private void clearSelection() {  
    226.         messageImage.setImageResource(R.drawable.message_unselected);  
    227.         messageText.setTextColor(Color.parseColor("#82858b"));  
    228.         contactsImage.setImageResource(R.drawable.contacts_unselected);  
    229.         contactsText.setTextColor(Color.parseColor("#82858b"));  
    230.         newsImage.setImageResource(R.drawable.news_unselected);  
    231.         newsText.setTextColor(Color.parseColor("#82858b"));  
    232.         settingImage.setImageResource(R.drawable.setting_unselected);  
    233.         settingText.setTextColor(Color.parseColor("#82858b"));  
    234.     }  
    235.   
    236.     /** 
    237.      * 将所有的Fragment都置为隐藏状态。 
    238.      *  
    239.      * @param transaction 
    240.      *            用于对Fragment执行操作的事务 
    241.      */  
    242.     private void hideFragments(FragmentTransaction transaction) {  
    243.         if (messageFragment != null) {  
    244.             transaction.hide(messageFragment);  
    245.         }  
    246.         if (contactsFragment != null) {  
    247.             transaction.hide(contactsFragment);  
    248.         }  
    249.         if (newsFragment != null) {  
    250.             transaction.hide(newsFragment);  
    251.         }  
    252.         if (settingFragment != null) {  
    253.             transaction.hide(settingFragment);  
    254.         }  
    255.     }  
    256. }  
    /**
     * 项目的主Activity,所有的Fragment都嵌入在这里。
     * 
     * @author guolin
     */
    public class MainActivity extends Activity implements OnClickListener {
    
    	/**
    	 * 用于展示消息的Fragment
    	 */
    	private MessageFragment messageFragment;
    
    	/**
    	 * 用于展示联系人的Fragment
    	 */
    	private ContactsFragment contactsFragment;
    
    	/**
    	 * 用于展示动态的Fragment
    	 */
    	private NewsFragment newsFragment;
    
    	/**
    	 * 用于展示设置的Fragment
    	 */
    	private SettingFragment settingFragment;
    
    	/**
    	 * 消息界面布局
    	 */
    	private View messageLayout;
    
    	/**
    	 * 联系人界面布局
    	 */
    	private View contactsLayout;
    
    	/**
    	 * 动态界面布局
    	 */
    	private View newsLayout;
    
    	/**
    	 * 设置界面布局
    	 */
    	private View settingLayout;
    
    	/**
    	 * 在Tab布局上显示消息图标的控件
    	 */
    	private ImageView messageImage;
    
    	/**
    	 * 在Tab布局上显示联系人图标的控件
    	 */
    	private ImageView contactsImage;
    
    	/**
    	 * 在Tab布局上显示动态图标的控件
    	 */
    	private ImageView newsImage;
    
    	/**
    	 * 在Tab布局上显示设置图标的控件
    	 */
    	private ImageView settingImage;
    
    	/**
    	 * 在Tab布局上显示消息标题的控件
    	 */
    	private TextView messageText;
    
    	/**
    	 * 在Tab布局上显示联系人标题的控件
    	 */
    	private TextView contactsText;
    
    	/**
    	 * 在Tab布局上显示动态标题的控件
    	 */
    	private TextView newsText;
    
    	/**
    	 * 在Tab布局上显示设置标题的控件
    	 */
    	private TextView settingText;
    
    	/**
    	 * 用于对Fragment进行管理
    	 */
    	private FragmentManager fragmentManager;
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		requestWindowFeature(Window.FEATURE_NO_TITLE);
    		setContentView(R.layout.activity_main);
    		// 初始化布局元素
    		initViews();
    		fragmentManager = getFragmentManager();
    		// 第一次启动时选中第0个tab
    		setTabSelection(0);
    	}
    
    	/**
    	 * 在这里获取到每个需要用到的控件的实例,并给它们设置好必要的点击事件。
    	 */
    	private void initViews() {
    		messageLayout = findViewById(R.id.message_layout);
    		contactsLayout = findViewById(R.id.contacts_layout);
    		newsLayout = findViewById(R.id.news_layout);
    		settingLayout = findViewById(R.id.setting_layout);
    		messageImage = (ImageView) findViewById(R.id.message_image);
    		contactsImage = (ImageView) findViewById(R.id.contacts_image);
    		newsImage = (ImageView) findViewById(R.id.news_image);
    		settingImage = (ImageView) findViewById(R.id.setting_image);
    		messageText = (TextView) findViewById(R.id.message_text);
    		contactsText = (TextView) findViewById(R.id.contacts_text);
    		newsText = (TextView) findViewById(R.id.news_text);
    		settingText = (TextView) findViewById(R.id.setting_text);
    		messageLayout.setOnClickListener(this);
    		contactsLayout.setOnClickListener(this);
    		newsLayout.setOnClickListener(this);
    		settingLayout.setOnClickListener(this);
    	}
    
    	@Override
    	public void onClick(View v) {
    		switch (v.getId()) {
    		case R.id.message_layout:
    			// 当点击了消息tab时,选中第1个tab
    			setTabSelection(0);
    			break;
    		case R.id.contacts_layout:
    			// 当点击了联系人tab时,选中第2个tab
    			setTabSelection(1);
    			break;
    		case R.id.news_layout:
    			// 当点击了动态tab时,选中第3个tab
    			setTabSelection(2);
    			break;
    		case R.id.setting_layout:
    			// 当点击了设置tab时,选中第4个tab
    			setTabSelection(3);
    			break;
    		default:
    			break;
    		}
    	}
    
    	/**
    	 * 根据传入的index参数来设置选中的tab页。
    	 * 
    	 * @param index
    	 *            每个tab页对应的下标。0表示消息,1表示联系人,2表示动态,3表示设置。
    	 */
    	private void setTabSelection(int index) {
    		// 每次选中之前先清楚掉上次的选中状态
    		clearSelection();
    		// 开启一个Fragment事务
    		FragmentTransaction transaction = fragmentManager.beginTransaction();
    		// 先隐藏掉所有的Fragment,以防止有多个Fragment显示在界面上的情况
    		hideFragments(transaction);
    		switch (index) {
    		case 0:
    			// 当点击了消息tab时,改变控件的图片和文字颜色
    			messageImage.setImageResource(R.drawable.message_selected);
    			messageText.setTextColor(Color.WHITE);
    			if (messageFragment == null) {
    				// 如果MessageFragment为空,则创建一个并添加到界面上
    				messageFragment = new MessageFragment();
    				transaction.add(R.id.content, messageFragment);
    			} else {
    				// 如果MessageFragment不为空,则直接将它显示出来
    				transaction.show(messageFragment);
    			}
    			break;
    		case 1:
    			// 当点击了联系人tab时,改变控件的图片和文字颜色
    			contactsImage.setImageResource(R.drawable.contacts_selected);
    			contactsText.setTextColor(Color.WHITE);
    			if (contactsFragment == null) {
    				// 如果ContactsFragment为空,则创建一个并添加到界面上
    				contactsFragment = new ContactsFragment();
    				transaction.add(R.id.content, contactsFragment);
    			} else {
    				// 如果ContactsFragment不为空,则直接将它显示出来
    				transaction.show(contactsFragment);
    			}
    			break;
    		case 2:
    			// 当点击了动态tab时,改变控件的图片和文字颜色
    			newsImage.setImageResource(R.drawable.news_selected);
    			newsText.setTextColor(Color.WHITE);
    			if (newsFragment == null) {
    				// 如果NewsFragment为空,则创建一个并添加到界面上
    				newsFragment = new NewsFragment();
    				transaction.add(R.id.content, newsFragment);
    			} else {
    				// 如果NewsFragment不为空,则直接将它显示出来
    				transaction.show(newsFragment);
    			}
    			break;
    		case 3:
    		default:
    			// 当点击了设置tab时,改变控件的图片和文字颜色
    			settingImage.setImageResource(R.drawable.setting_selected);
    			settingText.setTextColor(Color.WHITE);
    			if (settingFragment == null) {
    				// 如果SettingFragment为空,则创建一个并添加到界面上
    				settingFragment = new SettingFragment();
    				transaction.add(R.id.content, settingFragment);
    			} else {
    				// 如果SettingFragment不为空,则直接将它显示出来
    				transaction.show(settingFragment);
    			}
    			break;
    		}
    		transaction.commit();
    	}
    
    	/**
    	 * 清除掉所有的选中状态。
    	 */
    	private void clearSelection() {
    		messageImage.setImageResource(R.drawable.message_unselected);
    		messageText.setTextColor(Color.parseColor("#82858b"));
    		contactsImage.setImageResource(R.drawable.contacts_unselected);
    		contactsText.setTextColor(Color.parseColor("#82858b"));
    		newsImage.setImageResource(R.drawable.news_unselected);
    		newsText.setTextColor(Color.parseColor("#82858b"));
    		settingImage.setImageResource(R.drawable.setting_unselected);
    		settingText.setTextColor(Color.parseColor("#82858b"));
    	}
    
    	/**
    	 * 将所有的Fragment都置为隐藏状态。
    	 * 
    	 * @param transaction
    	 *            用于对Fragment执行操作的事务
    	 */
    	private void hideFragments(FragmentTransaction transaction) {
    		if (messageFragment != null) {
    			transaction.hide(messageFragment);
    		}
    		if (contactsFragment != null) {
    			transaction.hide(contactsFragment);
    		}
    		if (newsFragment != null) {
    			transaction.hide(newsFragment);
    		}
    		if (settingFragment != null) {
    			transaction.hide(settingFragment);
    		}
    	}
    }

    这个类中的注释已经写得非常详细了,下面我再带大家简单梳理一遍。在onCreate()方法中先是调用了initViews()来获取每个控件的实例,并给相应的控件设置好点击事件,然后调用setTabSelection()方法设置默认的选中项,这里传入的0说明默认选中第1个Tab项。

    那么setTabSelection()方法中又是如何处理的呢?可以看到,首先第一步是调用clearSelection()方法来清理掉之前的选中状态,然后开启一个Fragment事务,并隐藏掉所有的Fragment,以防止有多个Fragment显示在界面上。接下来根据传入的index参数判断出选中的是哪一个Tab项,并改变该Tab项的图标和文字颜色,然后将相应的Fragment添加到界面上。这里注意一个细节,我们添加Fragment的时候并没有使用replace()方法,而是会先判断一下该Fragment是否为空,如果是空的则调用add()方法添加一个进来,如果不是空的则直接调用show()方法显示出来即可。那么为什么没有使用replace()方法呢?这是因为replace()方法会将被替换掉的那个Fragment彻底地移除掉,该Fragment的生命周期就结束了。当再次点击刚才那个Tab项的时候,就会让该Fragment的生命周期重新开始,onCreate()、onCreateView()等方法都会重新执行一遍。这显然不是我们想要的,也和ActivityGroup的工作原理不符,因此最好的解决方案就是使用hide()和show()方法来隐藏和显示Fragment,这就不会让Fragment的生命周期重走一遍了。

    设置完默认选中项后,我们当然还可以通过点击Tab项来自由地切换界面,这就会进入到onClick()方法中。onClick()方法中的逻辑判断非常简单,当点击了消息标签时就会选中第1个tab项,点击联系人标签时就会选中第2个tab项,点击动态标签时就会选中第3个tab项,点击设置标签时就会选中第4个tab项。都是通过调用setTabSelection()方法来完成的,只是传入了不同的参数。

    好了,这样我们就将全部的代码都编写完成了,下面就来运行一下吧。整个Tab的界面有点类似于QQ的感觉,并且可以通过点击不同的Tab来切换界面,如下图所示:

    另外,这个Tab界面即使在横屏的情况下也有不错的适用性哦,如下图所示:

    这样,我们就成功使用Fragment编写出了和TabHost一样的效果。每个界面的具体逻辑就可以写在相应的Fragment里,效果和之前写在Activity里是差不多的。如此一来,我们终于可以和那个被废弃的ActivityGroup说再见了!

    好了,今天的讲解到此结束,有疑问的朋友请在下面留言

    路漫漫其修远兮 吾将上下而求索
  • 相关阅读:
    vue-cli 2.x升级到3.x版本, 和3.x降级到2.x版本命令
    vue-cli 2.x项目,删除打包线上环境的控制台打印
    vue-cli 2.x项目使用cross-env新建多个打包环境
    解决vue项目路由出现message: "Navigating to current location (XXX) is not allowed"的问题
    vue打包后,解决出现不到字体文件的错误
    js 网络图片转base64的方式(两种)
    vscode编译器,Settings Sync 同步插件,忘记GitHub token 和 Gist的解决办法
    输入两个时间,计算他们相差多少天多少时,多少秒
    老生常谈之js深拷贝与浅拷贝
    React Hooks 你不来了解下?
  • 原文地址:https://www.cnblogs.com/hudabing/p/3992248.html
Copyright © 2011-2022 走看看