Android Fragment初探和深入

Fragment初探


为了让界面可以在平板上更好地展示,Android在3.0版本引入了Fragment(碎片)功能,它非常类似于Activity,可以像Activity一样包含布局。Fragment通常是嵌套在Activity中使用的,现在想象这种场景:有两个Fragment,Fragment 1包含了一个ListView,每行显示一本书的标题。Fragment 2包含了TextView和ImageView,来显示书的详细内容和图片。


如果现在程序运行竖屏模式的平板或手机上,Fragment 1可能嵌入在一个Activity中,而Fragment 2可能嵌入在另一个Activity中,如下图所示:




而如果现在程序运行在横屏模式的平板上,两个Fragment就可以嵌入在同一个Activity中了,如下图所示:




由此可以看出,使用Fragment可以让我们更加充分地利用平板的屏幕空间,下面我们一起来探究下如何使用Fragment。


首先需要注意,Fragment是在3.0版本引入的,如果你使用的是3.0之前的系统,需要先导入android-support-v4的jar包才能使用Fragment功能。


新建一个项目叫做Fragments,然后在layout文件夹下新建一个名为fragment1.xml的布局文件:

[html]  view plain  copy
  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:background="#00ff00" >  
  5.   
  6.     <TextView  
  7.         android:layout_width="wrap_content"  
  8.         android:layout_height="wrap_content"  
  9.         android:text="This is fragment 1"  
  10.         android:textColor="#000000"  
  11.         android:textSize="25sp" />  
  12.   
  13. </LinearLayout>  

可以看到,这个布局文件非常简单,只有一个LinearLayout,里面加入了一个TextView。我们如法炮制再新建一个fragment2.xml :

[html]  view plain  copy
  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:background="#ffff00" >  
  5.   
  6.     <TextView  
  7.         android:layout_width="wrap_content"  
  8.         android:layout_height="wrap_content"  
  9.         android:text="This is fragment 2"  
  10.         android:textColor="#000000"  
  11.         android:textSize="25sp" />  
  12.   
  13. </LinearLayout>  

然后新建一个类Fragment1,这个类是继承自Fragment的:

[java]  view plain  copy
  1. public class Fragment1 extends Fragment {  
  2.   
  3.     @Override  
  4.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
  5.         return inflater.inflate(R.layout.fragment1, container, false);  
  6.     }  
  7.   
  8. }  
我们可以看到,这个类也非常简单,主要就是加载了我们刚刚写好的fragment1.xml布局文件并返回。同样的方法,我们再写好Fragment2 :
[java]  view plain  copy
  1. public class Fragment2 extends Fragment {  
  2.   
  3.     @Override  
  4.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
  5.         return inflater.inflate(R.layout.fragment2, container, false);  
  6.     }  
  7.   
  8. }  
然后打开或新建activity_main.xml作为主Activity的布局文件,在里面加入两个Fragment的引用,使用android:name前缀来引用具体的Fragment:
[html]  view plain  copy
  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:baselineAligned="false" >  
  5.   
  6.     <fragment  
  7.         android:id="@+id/fragment1"  
  8.         android:name="com.example.fragmentdemo.Fragment1"  
  9.         android:layout_width="0dip"  
  10.         android:layout_height="match_parent"  
  11.         android:layout_weight="1" />  
  12.   
  13.     <fragment  
  14.         android:id="@+id/fragment2"  
  15.         android:name="com.example.fragmentdemo.Fragment2"  
  16.         android:layout_width="0dip"  
  17.         android:layout_height="match_parent"  
  18.         android:layout_weight="1" />  
  19.   
  20. </LinearLayout>  
最后打开或新建MainActivity作为程序的主Activity,里面的代码非常简单,都是自动生成的:
[java]  view plain  copy
  1. public class MainActivity extends Activity {  
  2.   
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.activity_main);  
  7.     }  
  8.   
  9. }  

现在我们来运行一次程序,就会看到,一个Activity很融洽地包含了两个Fragment,这两个Fragment平分了整个屏幕,效果图如下:




动态添加Fragment


你已经学会了如何在XML中使用Fragment,但是这仅仅是Fragment最简单的功能而已。Fragment真正的强大之处在于可以动态地添加到Activity当中,因此这也是你必须要掌握的东西。当你学会了在程序运行时向Activity添加Fragment,程序的界面就可以定制的更加多样化。下面我们立刻来看看,如何动态添加Fragment。


还是在上一节代码的基础上修改,打开activity_main.xml,将其中对Fragment的引用都删除,只保留最外层的LinearLayout,并给它添加一个id,因为我们要动态添加Fragment,不用在XML里添加了,删除后代码如下:

[html]  view plain  copy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:id="@+id/main_layout"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:baselineAligned="false" >  
  6.   
  7. </LinearLayout>  
然后打开MainActivity,修改其中的代码如下所示:
[java]  view plain  copy
  1. public class MainActivity extends Activity {  
  2.   
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.activity_main);  
  7.         Display display = getWindowManager().getDefaultDisplay();  
  8.         if (display.getWidth() > display.getHeight()) {  
  9.             Fragment1 fragment1 = new Fragment1();  
  10.             getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit();  
  11.         } else {  
  12.             Fragment2 fragment2 = new Fragment2();  
  13.             getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment2).commit();  
  14.         }  
  15.     }  
  16.   
  17. }  

首先,我们要获取屏幕的宽度和高度,然后进行判断,如果屏幕宽度大于高度就添加fragment1,如果高度大于宽度就添加fragment2。动态添加Fragment主要分为4步:


1.获取到FragmentManager,在Activity中可以直接通过getFragmentManager得到。

2.开启一个事务,通过调用beginTransaction方法开启。

3.向容器内加入Fragment,一般使用replace方法实现,需要传入容器的id和Fragment的实例。

4.提交事务,调用commit方法提交。


现在运行一下程序,效果如下图所示:




如果你是在使用模拟器运行,按下ctrl + F11切换到竖屏模式。效果如下图所示:




Fragment的生命周期


和Activity一样,Fragment也有自己的生命周期,理解Fragment的生命周期非常重要,我们通过代码的方式来瞧一瞧Fragment的生命周期是什么样的:

[java]  view plain  copy
  1. public class Fragment1 extends Fragment {  
  2.     public static final String TAG = "Fragment1";  
  3.   
  4.     @Override  
  5.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
  6.         Log.d(TAG, "onCreateView");  
  7.         return inflater.inflate(R.layout.fragment1, container, false);  
  8.     }  
  9.   
  10.     @Override  
  11.     public void onAttach(Activity activity) {  
  12.         super.onAttach(activity);  
  13.         Log.d(TAG, "onAttach");  
  14.     }  
  15.   
  16.     @Override  
  17.     public void onCreate(Bundle savedInstanceState) {  
  18.         super.onCreate(savedInstanceState);  
  19.         Log.d(TAG, "onCreate");  
  20.     }  
  21.   
  22.     @Override  
  23.     public void onActivityCreated(Bundle savedInstanceState) {  
  24.         super.onActivityCreated(savedInstanceState);  
  25.         Log.d(TAG, "onActivityCreated");  
  26.     }  
  27.   
  28.     @Override  
  29.     public void onStart() {  
  30.         super.onStart();  
  31.         Log.d(TAG, "onStart");  
  32.     }  
  33.   
  34.     @Override  
  35.     public void onResume() {  
  36.         super.onResume();  
  37.         Log.d(TAG, "onResume");  
  38.     }  
  39.   
  40.     @Override  
  41.     public void onPause() {  
  42.         super.onPause();  
  43.         Log.d(TAG, "onPause");  
  44.     }  
  45.   
  46.     @Override  
  47.     public void onStop() {  
  48.         super.onStop();  
  49.         Log.d(TAG, "onStop");  
  50.     }  
  51.   
  52.     @Override  
  53.     public void onDestroyView() {  
  54.         super.onDestroyView();  
  55.         Log.d(TAG, "onDestroyView");  
  56.     }  
  57.   
  58.     @Override  
  59.     public void onDestroy() {  
  60.         super.onDestroy();  
  61.         Log.d(TAG, "onDestroy");  
  62.     }  
  63.   
  64.     @Override  
  65.     public void onDetach() {  
  66.         super.onDetach();  
  67.         Log.d(TAG, "onDetach");  
  68.     }  
  69.   
  70. }  

可以看到,上面的代码在每个生命周期的方法里都打印了日志,然后我们来运行一下程序,可以看到打印日志如下:




这时点击一下home键,打印日志如下:




如果你再重新进入进入程序,打印日志如下:




然后点击back键退出程序,打印日志如下:




看到这里,我相信大多数朋友已经非常明白了,因为这和Activity的生命周期太相似了。只是有几个Activity中没有的新方法,这里需要重点介绍一下:

  • onAttach方法:Fragment和Activity建立关联的时候调用。
  • onCreateView方法:为Fragment加载布局时调用。
  • onActivityCreated方法:当Activity中的onCreate方法执行完后调用。
  • onDestroyView方法:Fragment中的布局被移除时调用。
  • onDetach方法:Fragment和Activity解除关联的时候调用。


Fragment之间进行通信


通常情况下,Activity都会包含多个Fragment,这时多个Fragment之间如何进行通信就是个非常重要的问题了。我们通过一个例子来看一下,如何在一个Fragment中去访问另一个Fragment的视图。


还是在第一节代码的基础上修改,首先打开fragment2.xml,在这个布局里面添加一个按钮:

[html]  view plain  copy
  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.     android:background="#ffff00" >  
  6.   
  7.     <TextView  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="This is fragment 2"  
  11.         android:textColor="#000000"  
  12.         android:textSize="25sp" />  
  13.       
  14.     <Button   
  15.         android:id="@+id/button"  
  16.         android:layout_width="wrap_content"  
  17.         android:layout_height="wrap_content"  
  18.         android:text="Get fragment1 text"  
  19.         />  
  20.   
  21. </LinearLayout>  
然后打开fragment1.xml,为TextView添加一个id:
[html]  view plain  copy
  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:background="#00ff00" >  
  5.   
  6.     <TextView  
  7.         android:id="@+id/fragment1_text"  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="This is fragment 1"  
  11.         android:textColor="#000000"  
  12.         android:textSize="25sp" />  
  13.   
  14. </LinearLayout>  
接着打开Fragment2.java,添加onActivityCreated方法,并处理按钮的点击事件:
[java]  view plain  copy
  1. public class Fragment2 extends Fragment {  
  2.   
  3.     @Override  
  4.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
  5.         return inflater.inflate(R.layout.fragment2, container, false);  
  6.     }  
  7.   
  8.     @Override  
  9.     public void onActivityCreated(Bundle savedInstanceState) {  
  10.         super.onActivityCreated(savedInstanceState);  
  11.         Button button = (Button) getActivity().findViewById(R.id.button);  
  12.         button.setOnClickListener(new OnClickListener() {  
  13.             @Override  
  14.             public void onClick(View v) {  
  15.                 TextView textView = (TextView) getActivity().findViewById(R.id.fragment1_text);  
  16.                 Toast.makeText(getActivity(), textView.getText(), Toast.LENGTH_LONG).show();  
  17.             }  
  18.         });  
  19.     }  
  20.   
  21. }  

现在运行一下程序,并点击一下fragment2上的按钮,效果如下图所示:



我们可以看到,在fragment2中成功获取到了fragment1中的视图,并弹出Toast。这是怎么实现的呢?主要都是通过getActivity这个方法实现的。getActivity方法可以让Fragment获取到关联的Activity,然后再调用Activity的findViewById方法,就可以获取到和这个Activity关联的其它Fragment的视图了。



















深入:



        


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


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


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

[html]  view plain  copy
  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>  

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


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

[html]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent" >  
  5.   
  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>  

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


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

[java]  view plain  copy
  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. }  
后面就是依葫芦画瓢,把其它几个Fragment以及对应的布局创建出来。新建contacts_layout.xml作为联系人界面的布局,代码如下所示:
[html]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent" >  
  5.   
  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>  
再新建ContactsFragment继承自Fragment,代码如下所示:
[java]  view plain  copy
  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. }  
然后新建news_layout.xml作为动态界面的布局,代码如下所示:
[html]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent" >  
  5.   
  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>  
再新建NewsFragment继承自Fragment,代码如下所示:
[java]  view plain  copy
  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. }  
最后新建setting_layout.xml作为设置界面的布局,代码如下所示:
[html]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent" >  
  5.   
  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>  
再新建SettingFragment继承自Fragment,代码如下所示:
[java]  view plain  copy
  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. }  
这样我们就把每一个Fragment,以及它们所对应的布局文件都创建好了。接下来也就是最关键的步骤了,打开或新建MainActivity作为主Activity,代码如下所示:
[java]  view plain  copy
  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. }  
这个类中的注释已经写得非常详细了,下面我再带大家简单梳理一遍。在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初探


为了让界面可以在平板上更好地展示,Android在3.0版本引入了Fragment(碎片)功能,它非常类似于Activity,可以像Activity一样包含布局。Fragment通常是嵌套在Activity中使用的,现在想象这种场景:有两个Fragment,Fragment 1包含了一个ListView,每行显示一本书的标题。Fragment 2包含了TextView和ImageView,来显示书的详细内容和图片。


如果现在程序运行竖屏模式的平板或手机上,Fragment 1可能嵌入在一个Activity中,而Fragment 2可能嵌入在另一个Activity中,如下图所示:




而如果现在程序运行在横屏模式的平板上,两个Fragment就可以嵌入在同一个Activity中了,如下图所示:




由此可以看出,使用Fragment可以让我们更加充分地利用平板的屏幕空间,下面我们一起来探究下如何使用Fragment。


首先需要注意,Fragment是在3.0版本引入的,如果你使用的是3.0之前的系统,需要先导入android-support-v4的jar包才能使用Fragment功能。


新建一个项目叫做Fragments,然后在layout文件夹下新建一个名为fragment1.xml的布局文件:

[html]  view plain  copy
  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:background="#00ff00" >  
  5.   
  6.     <TextView  
  7.         android:layout_width="wrap_content"  
  8.         android:layout_height="wrap_content"  
  9.         android:text="This is fragment 1"  
  10.         android:textColor="#000000"  
  11.         android:textSize="25sp" />  
  12.   
  13. </LinearLayout>  

可以看到,这个布局文件非常简单,只有一个LinearLayout,里面加入了一个TextView。我们如法炮制再新建一个fragment2.xml :

[html]  view plain  copy
  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:background="#ffff00" >  
  5.   
  6.     <TextView  
  7.         android:layout_width="wrap_content"  
  8.         android:layout_height="wrap_content"  
  9.         android:text="This is fragment 2"  
  10.         android:textColor="#000000"  
  11.         android:textSize="25sp" />  
  12.   
  13. </LinearLayout>  

然后新建一个类Fragment1,这个类是继承自Fragment的:

[java]  view plain  copy
  1. public class Fragment1 extends Fragment {  
  2.   
  3.     @Override  
  4.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
  5.         return inflater.inflate(R.layout.fragment1, container, false);  
  6.     }  
  7.   
  8. }  
我们可以看到,这个类也非常简单,主要就是加载了我们刚刚写好的fragment1.xml布局文件并返回。同样的方法,我们再写好Fragment2 :
[java]  view plain  copy
  1. public class Fragment2 extends Fragment {  
  2.   
  3.     @Override  
  4.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
  5.         return inflater.inflate(R.layout.fragment2, container, false);  
  6.     }  
  7.   
  8. }  
然后打开或新建activity_main.xml作为主Activity的布局文件,在里面加入两个Fragment的引用,使用android:name前缀来引用具体的Fragment:
[html]  view plain  copy
  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:baselineAligned="false" >  
  5.   
  6.     <fragment  
  7.         android:id="@+id/fragment1"  
  8.         android:name="com.example.fragmentdemo.Fragment1"  
  9.         android:layout_width="0dip"  
  10.         android:layout_height="match_parent"  
  11.         android:layout_weight="1" />  
  12.   
  13.     <fragment  
  14.         android:id="@+id/fragment2"  
  15.         android:name="com.example.fragmentdemo.Fragment2"  
  16.         android:layout_width="0dip"  
  17.         android:layout_height="match_parent"  
  18.         android:layout_weight="1" />  
  19.   
  20. </LinearLayout>  
最后打开或新建MainActivity作为程序的主Activity,里面的代码非常简单,都是自动生成的:
[java]  view plain  copy
  1. public class MainActivity extends Activity {  
  2.   
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.activity_main);  
  7.     }  
  8.   
  9. }  

现在我们来运行一次程序,就会看到,一个Activity很融洽地包含了两个Fragment,这两个Fragment平分了整个屏幕,效果图如下:




动态添加Fragment


你已经学会了如何在XML中使用Fragment,但是这仅仅是Fragment最简单的功能而已。Fragment真正的强大之处在于可以动态地添加到Activity当中,因此这也是你必须要掌握的东西。当你学会了在程序运行时向Activity添加Fragment,程序的界面就可以定制的更加多样化。下面我们立刻来看看,如何动态添加Fragment。


还是在上一节代码的基础上修改,打开activity_main.xml,将其中对Fragment的引用都删除,只保留最外层的LinearLayout,并给它添加一个id,因为我们要动态添加Fragment,不用在XML里添加了,删除后代码如下:

[html]  view plain  copy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:id="@+id/main_layout"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:baselineAligned="false" >  
  6.   
  7. </LinearLayout>  
然后打开MainActivity,修改其中的代码如下所示:
[java]  view plain  copy
  1. public class MainActivity extends Activity {  
  2.   
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.activity_main);  
  7.         Display display = getWindowManager().getDefaultDisplay();  
  8.         if (display.getWidth() > display.getHeight()) {  
  9.             Fragment1 fragment1 = new Fragment1();  
  10.             getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit();  
  11.         } else {  
  12.             Fragment2 fragment2 = new Fragment2();  
  13.             getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment2).commit();  
  14.         }  
  15.     }  
  16.   
  17. }  

首先,我们要获取屏幕的宽度和高度,然后进行判断,如果屏幕宽度大于高度就添加fragment1,如果高度大于宽度就添加fragment2。动态添加Fragment主要分为4步:


1.获取到FragmentManager,在Activity中可以直接通过getFragmentManager得到。

2.开启一个事务,通过调用beginTransaction方法开启。

3.向容器内加入Fragment,一般使用replace方法实现,需要传入容器的id和Fragment的实例。

4.提交事务,调用commit方法提交。


现在运行一下程序,效果如下图所示:




如果你是在使用模拟器运行,按下ctrl + F11切换到竖屏模式。效果如下图所示:




Fragment的生命周期


和Activity一样,Fragment也有自己的生命周期,理解Fragment的生命周期非常重要,我们通过代码的方式来瞧一瞧Fragment的生命周期是什么样的:

[java]  view plain  copy
  1. public class Fragment1 extends Fragment {  
  2.     public static final String TAG = "Fragment1";  
  3.   
  4.     @Override  
  5.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
  6.         Log.d(TAG, "onCreateView");  
  7.         return inflater.inflate(R.layout.fragment1, container, false);  
  8.     }  
  9.   
  10.     @Override  
  11.     public void onAttach(Activity activity) {  
  12.         super.onAttach(activity);  
  13.         Log.d(TAG, "onAttach");  
  14.     }  
  15.   
  16.     @Override  
  17.     public void onCreate(Bundle savedInstanceState) {  
  18.         super.onCreate(savedInstanceState);  
  19.         Log.d(TAG, "onCreate");  
  20.     }  
  21.   
  22.     @Override  
  23.     public void onActivityCreated(Bundle savedInstanceState) {  
  24.         super.onActivityCreated(savedInstanceState);  
  25.         Log.d(TAG, "onActivityCreated");  
  26.     }  
  27.   
  28.     @Override  
  29.     public void onStart() {  
  30.         super.onStart();  
  31.         Log.d(TAG, "onStart");  
  32.     }  
  33.   
  34.     @Override  
  35.     public void onResume() {  
  36.         super.onResume();  
  37.         Log.d(TAG, "onResume");  
  38.     }  
  39.   
  40.     @Override  
  41.     public void onPause() {  
  42.         super.onPause();  
  43.         Log.d(TAG, "onPause");  
  44.     }  
  45.   
  46.     @Override  
  47.     public void onStop() {  
  48.         super.onStop();  
  49.         Log.d(TAG, "onStop");  
  50.     }  
  51.   
  52.     @Override  
  53.     public void onDestroyView() {  
  54.         super.onDestroyView();  
  55.         Log.d(TAG, "onDestroyView");  
  56.     }  
  57.   
  58.     @Override  
  59.     public void onDestroy() {  
  60.         super.onDestroy();  
  61.         Log.d(TAG, "onDestroy");  
  62.     }  
  63.   
  64.     @Override  
  65.     public void onDetach() {  
  66.         super.onDetach();  
  67.         Log.d(TAG, "onDetach");  
  68.     }  
  69.   
  70. }  

可以看到,上面的代码在每个生命周期的方法里都打印了日志,然后我们来运行一下程序,可以看到打印日志如下:




这时点击一下home键,打印日志如下:




如果你再重新进入进入程序,打印日志如下:




然后点击back键退出程序,打印日志如下:




看到这里,我相信大多数朋友已经非常明白了,因为这和Activity的生命周期太相似了。只是有几个Activity中没有的新方法,这里需要重点介绍一下:

  • onAttach方法:Fragment和Activity建立关联的时候调用。
  • onCreateView方法:为Fragment加载布局时调用。
  • onActivityCreated方法:当Activity中的onCreate方法执行完后调用。
  • onDestroyView方法:Fragment中的布局被移除时调用。
  • onDetach方法:Fragment和Activity解除关联的时候调用。


Fragment之间进行通信


通常情况下,Activity都会包含多个Fragment,这时多个Fragment之间如何进行通信就是个非常重要的问题了。我们通过一个例子来看一下,如何在一个Fragment中去访问另一个Fragment的视图。


还是在第一节代码的基础上修改,首先打开fragment2.xml,在这个布局里面添加一个按钮:

[html]  view plain  copy
  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.     android:background="#ffff00" >  
  6.   
  7.     <TextView  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="This is fragment 2"  
  11.         android:textColor="#000000"  
  12.         android:textSize="25sp" />  
  13.       
  14.     <Button   
  15.         android:id="@+id/button"  
  16.         android:layout_width="wrap_content"  
  17.         android:layout_height="wrap_content"  
  18.         android:text="Get fragment1 text"  
  19.         />  
  20.   
  21. </LinearLayout>  
然后打开fragment1.xml,为TextView添加一个id:
[html]  view plain  copy
  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:background="#00ff00" >  
  5.   
  6.     <TextView  
  7.         android:id="@+id/fragment1_text"  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="This is fragment 1"  
  11.         android:textColor="#000000"  
  12.         android:textSize="25sp" />  
  13.   
  14. </LinearLayout>  
接着打开Fragment2.java,添加onActivityCreated方法,并处理按钮的点击事件:
[java]  view plain  copy
  1. public class Fragment2 extends Fragment {  
  2.   
  3.     @Override  
  4.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
  5.         return inflater.inflate(R.layout.fragment2, container, false);  
  6.     }  
  7.   
  8.     @Override  
  9.     public void onActivityCreated(Bundle savedInstanceState) {  
  10.         super.onActivityCreated(savedInstanceState);  
  11.         Button button = (Button) getActivity().findViewById(R.id.button);  
  12.         button.setOnClickListener(new OnClickListener() {  
  13.             @Override  
  14.             public void onClick(View v) {  
  15.                 TextView textView = (TextView) getActivity().findViewById(R.id.fragment1_text);  
  16.                 Toast.makeText(getActivity(), textView.getText(), Toast.LENGTH_LONG).show();  
  17.             }  
  18.         });  
  19.     }  
  20.   
  21. }  

现在运行一下程序,并点击一下fragment2上的按钮,效果如下图所示:



我们可以看到,在fragment2中成功获取到了fragment1中的视图,并弹出Toast。这是怎么实现的呢?主要都是通过getActivity这个方法实现的。getActivity方法可以让Fragment获取到关联的Activity,然后再调用Activity的findViewById方法,就可以获取到和这个Activity关联的其它Fragment的视图了。

猜你喜欢

转载自blog.csdn.net/weixin_38775077/article/details/80734853
今日推荐