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

我们都知道,Android上的界面展示都是通过Activity实现的,Activity实在是太常用了,我相信大家都已经非常熟悉了,这里就不再赘述。

但是Activity也有它的局限性,同样的界面在手机上显示可能很好看,在平板上就未必了,因为平板的屏幕非常大,手机的界面放在平板上可能会有过分被拉长、控件间距过大等情况。这个时候更好的体验效果是在Activity中嵌入"小Activity",然后每个"小Activity"又可以拥有自己的布局。因此,我们今天的主角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的布局文件:

  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. <TextView
  6. android:layout_width="wrap_content"
  7. android:layout_height="wrap_content"
  8. android:text="This is fragment 1"
  9. android:textColor="#000000"
  10. android:textSize="25sp" />
  11. </LinearLayout>

可以看到,这个布局文件非常简单,只有一个LinearLayout,里面加入了一个TextView。我们如法炮制再新建一个fragment2.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:background="#ffff00" >
  5. <TextView
  6. android:layout_width="wrap_content"
  7. android:layout_height="wrap_content"
  8. android:text="This is fragment 2"
  9. android:textColor="#000000"
  10. android:textSize="25sp" />
  11. </LinearLayout>

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

  1. public class Fragment1 extends Fragment {
  2. @Override
  3. public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  4. return inflater.inflate(R.layout.fragment1, container, false);
  5. }
  6. }

我们可以看到,这个类也非常简单,主要就是加载了我们刚刚写好的fragment1.xml布局文件并返回。同样的方法,我们再写好Fragment2 :

  1. public class Fragment2 extends Fragment {
  2. @Override
  3. public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  4. return inflater.inflate(R.layout.fragment2, container, false);
  5. }
  6. }

然后打开或新建activity_main.xml作为主Activity的布局文件,在里面加入两个Fragment的引用,使用android:name前缀来引用具体的Fragment:

  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. <fragment
  6. android:id="@+id/fragment1"
  7. android:name="com.example.fragmentdemo.Fragment1"
  8. android:layout_width="0dip"
  9. android:layout_height="match_parent"
  10. android:layout_weight="1" />
  11. <fragment
  12. android:id="@+id/fragment2"
  13. android:name="com.example.fragmentdemo.Fragment2"
  14. android:layout_width="0dip"
  15. android:layout_height="match_parent"
  16. android:layout_weight="1" />
  17. </LinearLayout>

最后打开或新建MainActivity作为程序的主Activity,里面的代码非常简单,都是自动生成的:

  1. public class MainActivity extends Activity {
  2. @Override
  3. protected void onCreate(Bundle savedInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. setContentView(R.layout.activity_main);
  6. }
  7. }

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

动态添加Fragment

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

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

  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. </LinearLayout>

然后打开MainActivity,修改其中的代码如下所示:

  1. public class MainActivity extends Activity {
  2. @Override
  3. protected void onCreate(Bundle savedInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. setContentView(R.layout.activity_main);
  6. Display display = getWindowManager().getDefaultDisplay();
  7. if (display.getWidth() > display.getHeight()) {
  8. Fragment1 fragment1 = new Fragment1();
  9. getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit();
  10. } else {
  11. Fragment2 fragment2 = new Fragment2();
  12. getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment2).commit();
  13. }
  14. }
  15. }

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

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

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

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

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

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

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

Fragment的生命周期

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

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

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

这时点击一下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,在这个布局里面添加一个按钮:

  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. <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. <Button
  13. android:id="@+id/button"
  14. android:layout_width="wrap_content"
  15. android:layout_height="wrap_content"
  16. android:text="Get fragment1 text"
  17. />
  18. </LinearLayout>

然后打开fragment1.xml,为TextView添加一个id:

  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. <TextView
  6. android:id="@+id/fragment1_text"
  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. </LinearLayout>

接着打开Fragment2.java,添加onActivityCreated方法,并处理按钮的点击事件:

  1. public class Fragment2 extends Fragment {
  2. @Override
  3. public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  4. return inflater.inflate(R.layout.fragment2, container, false);
  5. }
  6. @Override
  7. public void onActivityCreated(Bundle savedInstanceState) {
  8. super.onActivityCreated(savedInstanceState);
  9. Button button = (Button) getActivity().findViewById(R.id.button);
  10. button.setOnClickListener(new OnClickListener() {
  11. @Override
  12. public void onClick(View v) {
  13. TextView textView = (TextView) getActivity().findViewById(R.id.fragment1_text);
  14. Toast.makeText(getActivity(), textView.getText(), Toast.LENGTH_LONG).show();
  15. }
  16. });
  17. }
  18. }

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

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

好了,以上就是关于Fragment你所须知道的一切。如果想要切身体验一下Fragment的实战,请继续阅读 Android手机平板两不误,使用Fragment实现兼容手机和平板的程序 以及 Android Fragment应用实战,使用碎片向ActivityGroup说再见

Android Fragment完全解析的更多相关文章

  1. Android Fragment完全解析,关于碎片你所需知道的一切

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/8881711 我们都知道,Android上的界面展示都是通过Activity实现的, ...

  2. Android Fragment 完全解析

    参考文章:http://blog.csdn.net/guolin_blog/article/details/8881711 http://blog.csdn.net/guolin_blog/artic ...

  3. Android Fragment完全解析,关于碎片你所需知道的一切 (转)。

    我们都知道,Android上的界面展示都是通过Activity实现的,Activity实在是太常用了,我相信大家都已经非常熟悉了,这里就不再赘述. 但是Activity也有它的局限性,同样的界面在手机 ...

  4. (转) Android Fragment完全解析,关于碎片你所需知道的一切

    我们都知道,Android上的界面展示都是通过Activity实现的,Activity实在是太常用了,我相信大家都已经非常熟悉了,这里就不再赘述. 但是Activity也有它的局限性,同样的界面在手机 ...

  5. Android Fragment 初步解析

    Fragment经常在我们的开发中见到,但是自我感觉对Fragment的理解还是处于初级的阶段,接下来我将用几篇文章尽量深的解析Fragment 让我们开始吧!!! Fragment的生命周期 Fra ...

  6. Android Fragment 深度解析

    1.Fragment的产生与介绍 Android运行在各种各样的设备中,有小屏幕的手机,超大屏的平板甚至电视.针对屏幕尺寸的差距,很多情况下,都是先针对手机开发一套app,然后拷贝一份,修改布局以适应 ...

  7. Android Fragment应用实战

    现在Fragment的应用真的是越来越广泛了,之前Android在3.0版本加入Fragment的时候,主要是为了解决Android Pad屏幕比较大,空间不能充分利用的问题,但现在即使只是在手机上, ...

  8. Android Fragment应用实战,使用碎片向ActivityGroup说再见

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/13171191 现在Fragment的应用真的是越来越广泛了,之前Android在3 ...

  9. Android Fragment碎片

    什么是碎片? 碎片(Fragment)是一种可以嵌入在活动当中的UI片段,它能让程序更加合理和充分地利用大屏幕的空间,因而在平板上应用的非常广泛.可以把Fragment当成Activity一个界面的一 ...

随机推荐

  1. linux awk 一看就懂

    awk是什么 awk是linux环境下的一个命令行工具,但是由于awk强大的能力,我们可以为awk工具传递一个字符串,该字符串的内容类似一种编程语言的语法,我们可以称其为Awk语言,而awk工具本身则 ...

  2. Eclipse引入外部Jar在发布时没有自动带入,导致出现ClassNoFound错误

    今天换了一台电脑重新配置环境调试老程序的时候出现链接数据库错误java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver提示. ...

  3. EasyDarwin不能保存HLS列表的解决方案

    官网: easydarwin.org 安装过程 http://doc.easydarwin.org/EasyDarwin/README/ 安装客户端,iVMS-4200 客户端,并运行. 在设备管理里 ...

  4. 在UWP应用中加入Cortana语音指令集

    本文介绍小娜语音指令集的使用场景,如何将UWP应用接入小娜的语音指令集,使用户直接通过小娜启动应用并使用应用中 一些轻量级的功能.文中以必应词典作为实例讲解必应词典UWP版本是如何接入小娜语音功能的. ...

  5. ReentrantLock实现原理深入探究

    前言 这篇文章被归到Java基础分类中,其实真的一点都不基础.网上写ReentrantLock的使用.ReentrantLock和synchronized的区别的文章很多,研究ReentrantLoc ...

  6. HOOK技术的一些简单总结

    好久没写博客了, 一个月一篇还是要尽量保证,今天谈下Hook技术. 在Window平台上开发任何稍微底层一点的东西,基本上都是Hook满天飞, 普通应用程序如此,安全软件更是如此, 这里简单记录一些常 ...

  7. 由ASP.NET所谓前台调用后台、后台调用前台想到HTTP——实践篇(二)

    在由ASP.NET所谓前台调用后台.后台调用前台想到HTTP——理论篇中描述了一下ASP.NET新手的三个问题及相关的HTTP协议内容,在由ASP.NET所谓前台调用后台.后台调用前台想到HTTP—— ...

  8. NanoProfiler - 适合生产环境的性能监控类库 之 基本功能篇

    背景 NanoProfiler是一个EF Learning Labs出品的免费性能监控类库(即将开源).它的思想和使用方式类似于MiniProfiler的.但是,设计理念有较大差异. MiniProf ...

  9. Git学习笔记(2)——版本的回退,和暂存区的理解

    本文主要记录了版本的回退,以及工作区,暂存区概念的理解. //开始之前,先回顾上次的内容,修改文件如下,并提交到版本库. Git is a distributed version control sy ...

  10. IOS 多线程05-OperationQueue 、GCD详解

      注:本人是翻译过来,并且加上本人的一点见解. 1. 开始 目前在 iOS中有两套先进的同步 API 可供我们使用:操作队列OperationQueue和 GCD .其中 GCD 是基于 C 的底层 ...