Android Fragment 完全解析#


转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/37970961

自从Fragment出现,曾经有段时间,感觉大家谈什么都能跟Fragment谈上关系,做什么都要问下Fragment能实现不~~~哈哈,是不是有点过~~~

本篇博客力求为大家说明Fragment如何产生,什么是Fragment,Fragment生命周期,如何静态和动态的使用Fragment,Fragment回退栈,Fragment事务;以及Fragment的一些特殊用途,例如:没有布局的Fragment有何用处?Fragment如何与Activity交互?Fragment如何创建对话框?Fragment如何与ActionBar集成等等。

1、Fragment的产生与介绍

Android运行在各种各样的设备中,有小屏幕的手机,超大屏的平板甚至电视。针对屏幕尺寸的差距,很多情况下,都是先针对手机开发一套App,然后拷贝一份,修改布局以适应平板神马超级大屏的。难道无法做到一个App可以同时适应手机和平板么,当然了,必须有啊。Fragment的出现就是为了解决这样的问题。你可以把Fragment当成Activity的一个界面的一个组成部分,甚至Activity的界面可以完全有不同的Fragment组成,更帅气的是Fragment拥有自己的生命周期和接收、处理用户的事件,这样就不必在Activity写一堆控件的事件处理的代码了。更为重要的是,你可以动态的添加、替换和移除某个Fragment。

2、Fragment的生命周期

Fragment必须是依存与Activity而存在的,因此Activity的生命周期会直接影响到Fragment的生命周期。官网这张图很好的说明了两者生命周期的关系:

只有真正的掌握 生命周期 才能更好的运用frgment . 1.onAttach()
作用:fragment已经关联到activity,这个时候 activity已经传进来了, 获得activity的传递的值 就可以进行 与activity的通信里, 当然也可以使用getActivity(),前提是这个fragment已经和宿主的activity关联,并且没有脱离,有且只有调用一次。 2.onCreate() 系统创建fragment的时候回调他,在他里面实例化一些变量这些个变量主要是:当你 暂停 停止的时候 你想保持的数据 他只调用一次。

3.onCreateView()

第一次使用的时候 fragment会在这上面画一个layout出来, 为了可以画控件 要返回一个 布局的view,也可以返回null j 就什么都没有显示。当系统用到fragment的时候 fragment就要返回他的view,越快越好 ,所以尽量在这里不要做耗时操作,比如从数据库加载大量数据

4onActivityCreated()

当Activity中的onCreate方法执行完后调用。

注意了:
从这句官方的话可以看出:当执行onActivityCreated()的时候 activity的onCreate才刚完成。 所以在onActivityCreated()调用之前 activity的onCreate可能还没有完成, 所以不能再 onCreateView()中进行 与activity有交互的UI操作,UI交互操作可以在onActivityCreated()里面进行。 所以呢,这个方法主要是初始化那些你需要你的父Activity或者Fragment的UI已经被完 整初始化才能初始化的元素。

5.onStart()

和activity一致,启动Fragement 启动时回调,,此时Fragement可见。
6.onResume()

和activity一致 在activity中运行是可见的。激活, Fragement 进入前台, 可获取焦点时激活。

7.onPause()

和activity一致 其他的activity获得焦点,这个仍然可见第一次调用的时候,指的是 用户 离开这个fragment(并不是被销毁)
通常用于 用户的提交(可能用户离开后不会回来了)
8.onStop()

和activity一致, fragment不可见的, 可能情况:activity被stopped了或者 fragment被移除但被,加入到回退栈中,一个stopped的fragment仍然是活着的如果长时间不用也会被移除。

9. onDestroyView()

Fragment中的布局被移除时调用。表示fragemnt销毁相关联的UI布局, 清除所有跟视图相关的资源。

然后这个知识移除视图 并没有销毁而且还没有脱离activity

10.onDestroy()

销毁fragment对象, 跟activity类似了。
11.onDetach()

Fragment和Activity解除关联的时候调用。 脱离activity。

3、静态的使用Fragment

嘿嘿,终于到使用的时刻了~~

这是使用Fragment最简单的一种方式,把Fragment当成普通的控件,直接写在Activity的布局文件中。步骤:

1、继承Fragment,重写onCreateView决定Fragemnt的布局

2、在Activity中声明此Fragment,就当和普通的View一样

Fragment生命周期执行流程(注意红色的不是生命周期方法):
Fragment创建:setUserVisibleHint()->onAttach()->onCreate()->onCreateView()->onActivityCreated()->onStart()->onResume();
Fragment变为不可见状态(锁屏、回到桌面、被Activity完全覆盖):onPause()->onSaveInstanceState()->onStop();
Fragment变为部分可见状态(打开Dialog样式的Activity):onPause()->onSaveInstanceState();
Fragment由不可见变为活动状态:onStart()->OnResume();
Fragment由部分可见变为活动状态:onResume();
退出应用:onPause()->onStop()->onDestroyView()->onDestroy()->onDetach()(注意退出不会调用onSaveInstanceState方法,因为是人为退出,没有必要再保存数据);
Fragment被回收又重新创建:被回收执行onPause()->onSaveInstanceState()->onStop()->onDestroyView()->onDestroy()->onDetach(),重新创建执行onAttach()->onCreate()->onCreateView()->onActivityCreated()->onStart()->onResume()->setUserVisibleHint();
横竖屏切换:与Fragment被回收又重新创建一样。

下面展示一个例子(我使用2个Fragment作为Activity的布局,一个Fragment用于标题布局,一个Fragment用于内容布局):

TitleFragment的布局文件:

[html]view plaincopy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="45dp"
  5. android:background="@drawable/title_bar">
  6. <ImageButton
  7. android:id="@+id/id_title_left_btn"
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"
  10. android:layout_centerVertical="true"
  11. android:layout_marginLeft="3dp"
  12. android:background="@drawable/showleft_selector"/>
  13. <TextView
  14. android:layout_width="fill_parent"
  15. android:layout_height="fill_parent"
  16. android:gravity="center"
  17. android:text="我不是微信"
  18. android:textColor="#fff"
  19. android:textSize="20sp"
  20. android:textStyle="bold"/>
  21. </RelativeLayout>


TitleFragment

[java]view plaincopy
  1. packagecom.zhy.zhy_fragments;
  2. importandroid.app.Fragment;
  3. importandroid.os.Bundle;
  4. importandroid.view.LayoutInflater;
  5. importandroid.view.View;
  6. importandroid.view.View.OnClickListener;
  7. importandroid.view.ViewGroup;
  8. importandroid.widget.ImageButton;
  9. importandroid.widget.Toast;
  10. publicclassTitleFragmentextendsFragment
  11. {
  12. privateImageButtonmLeftMenu;
  13. @Override
  14. publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,
  15. BundlesavedInstanceState)
  16. {
  17. Viewview=inflater.inflate(R.layout.fragment_title,container,false);
  18. mLeftMenu=(ImageButton)view.findViewById(R.id.id_title_left_btn);
  19. mLeftMenu.setOnClickListener(newOnClickListener()
  20. {
  21. @Override
  22. publicvoidonClick(Viewv)
  23. {
  24. Toast.makeText(getActivity(),
  25. "iamanImageButtoninTitleFragment!",
  26. Toast.LENGTH_SHORT).show();
  27. }
  28. });
  29. returnview;
  30. }
  31. }


同理还有ContentFragment的其布局文件:

[html]view plaincopy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical">
  6. <TextView
  7. android:layout_width="fill_parent"
  8. android:layout_height="fill_parent"
  9. android:gravity="center"
  10. android:text="使用Fragment做主面板"
  11. android:textSize="20sp"
  12. android:textStyle="bold"/>
  13. </LinearLayout>

[java]view plaincopy
  1. packagecom.zhy.zhy_fragments;
  2. importandroid.app.Fragment;
  3. importandroid.os.Bundle;
  4. importandroid.view.LayoutInflater;
  5. importandroid.view.View;
  6. importandroid.view.ViewGroup;
  7. publicclassContentFragmentextendsFragment
  8. {
  9. @Override
  10. publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,
  11. BundlesavedInstanceState)
  12. {
  13. returninflater.inflate(R.layout.fragment_content,container,false);
  14. }
  15. }


MainActivity

[java]view plaincopy
  1. packagecom.zhy.zhy_fragments;
  2. importandroid.app.Activity;
  3. importandroid.os.Bundle;
  4. importandroid.view.Window;
  5. publicclassMainActivityextendsActivity
  6. {
  7. @Override
  8. protectedvoidonCreate(BundlesavedInstanceState)
  9. {
  10. super.onCreate(savedInstanceState);
  11. requestWindowFeature(Window.FEATURE_NO_TITLE);
  12. setContentView(R.layout.activity_main);
  13. }
  14. }


Activity的布局文件:

[java]view plaincopy
  1. <RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent">
  5. <fragment
  6. android:id="@+id/id_fragment_title"
  7. android:name="com.zhy.zhy_fragments.TitleFragment"
  8. android:layout_width="fill_parent"
  9. android:layout_height="45dp"/>
  10. <fragment
  11. android:layout_below="@id/id_fragment_title"
  12. android:id="@+id/id_fragment_content"
  13. android:name="com.zhy.zhy_fragments.ContentFragment"
  14. android:layout_width="fill_parent"
  15. android:layout_height="fill_parent"/>
  16. </RelativeLayout>


是不是把Fragment当成普通的View一样声明在Activity的布局文件中,然后所有控件的事件处理等代码都由各自的Fragment去处理,瞬间觉得Activity好干净有木有~~代码的可读性、复用性以及可维护性是不是瞬间提升了~~~下面看下效果图:

4、动态的使用Fragment

上面已经演示了,最简单的使用Fragment的方式~下面介绍如何动态的添加、更新、以及删除Fragment

为了动态使用Fragment,我们修改一下Actvity的布局文件,中间使用一个FrameLayout,下面添加四个按钮~~~嘿嘿~~不是微信的按钮- -!

[html]view plaincopy
  1. <RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent">
  5. <fragment
  6. android:id="@+id/id_fragment_title"
  7. android:name="com.zhy.zhy_fragments.TitleFragment"
  8. android:layout_width="fill_parent"
  9. android:layout_height="45dp"/>
  10. <include
  11. android:id="@+id/id_ly_bottombar"
  12. android:layout_width="fill_parent"
  13. android:layout_height="55dp"
  14. android:layout_alignParentBottom="true"
  15. layout="@layout/bottombar"/>
  16. <FrameLayout
  17. android:id="@+id/id_content"
  18. android:layout_width="fill_parent"
  19. android:layout_height="fill_parent"
  20. android:layout_above="@id/id_ly_bottombar"
  21. android:layout_below="@id/id_fragment_title"/>
  22. </RelativeLayout>


底部四个按钮的布局就不贴了,到时看效果图就明白了~~

下面主Activity

[java]view plaincopy
  1. packagecom.zhy.zhy_fragments;
  2. importandroid.app.Activity;
  3. importandroid.app.FragmentManager;
  4. importandroid.app.FragmentTransaction;
  5. importandroid.os.Bundle;
  6. importandroid.view.View;
  7. importandroid.view.View.OnClickListener;
  8. importandroid.view.Window;
  9. importandroid.widget.LinearLayout;
  10. publicclassMainActivityextendsActivityimplementsOnClickListener
  11. {
  12. privateLinearLayoutmTabWeixin;
  13. privateLinearLayoutmTabFriend;
  14. privateContentFragmentmWeixin;
  15. privateFriendFragmentmFriend;
  16. @Override
  17. protectedvoidonCreate(BundlesavedInstanceState)
  18. {
  19. super.onCreate(savedInstanceState);
  20. requestWindowFeature(Window.FEATURE_NO_TITLE);
  21. setContentView(R.layout.activity_main);
  22. //初始化控件和声明事件
  23. mTabWeixin=(LinearLayout)findViewById(R.id.tab_bottom_weixin);
  24. mTabFriend=(LinearLayout)findViewById(R.id.tab_bottom_friend);
  25. mTabWeixin.setOnClickListener(this);
  26. mTabFriend.setOnClickListener(this);
  27. //设置默认的Fragment
  28. setDefaultFragment();
  29. }
  30. privatevoidsetDefaultFragment()
  31. {
  32. FragmentManagerfm=getFragmentManager();
  33. FragmentTransactiontransaction=fm.beginTransaction();
  34. mWeixin=newContentFragment();
  35. transaction.replace(R.id.id_content,mWeixin);
  36. transaction.commit();
  37. }
  38. @Override
  39. publicvoidonClick(Viewv)
  40. {
  41. FragmentManagerfm=getFragmentManager();
  42. //开启Fragment事务
  43. FragmentTransactiontransaction=fm.beginTransaction();
  44. switch(v.getId())
  45. {
  46. caseR.id.tab_bottom_weixin:
  47. if(mWeixin==null)
  48. {
  49. mWeixin=newContentFragment();
  50. }
  51. //使用当前Fragment的布局替代id_content的控件
  52. transaction.replace(R.id.id_content,mWeixin);
  53. break;
  54. caseR.id.tab_bottom_friend:
  55. if(mFriend==null)
  56. {
  57. mFriend=newFriendFragment();
  58. }
  59. transaction.replace(R.id.id_content,mFriend);
  60. break;
  61. }
  62. //transaction.addToBackStack();
  63. //事务提交
  64. transaction.commit();
  65. }
  66. }


可以看到我们使用FragmentManager对Fragment进行了动态的加载,这里使用的是replace方法~~下一节我会详细介绍FragmentManager的常用API。

注:如果使用Android3.0以下的版本,需要引入v4的包,然后Activity继承FragmentActivity,然后通过getSupportFragmentManager获得FragmentManager。不过还是建议版Menifest文件的uses-sdk的minSdkVersion和targetSdkVersion都改为11以上,这样就不必引入v4包了。

代码中间还有两个Fragment的子类,ContentFragment上面已经见过,FriendFragment其实类似:

[java]view plaincopy
  1. packagecom.zhy.zhy_fragments;
  2. importandroid.app.Fragment;
  3. importandroid.os.Bundle;
  4. importandroid.view.LayoutInflater;
  5. importandroid.view.View;
  6. importandroid.view.ViewGroup;
  7. publicclassFriendFragmentextendsFragment
  8. {
  9. @Override
  10. publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,
  11. BundlesavedInstanceState)
  12. {
  13. returninflater.inflate(R.layout.fragment_friend,container,false);
  14. }
  15. }


效果图:

可以看到很好的实现了效果,其实这个效果以前的博客中也出现过,在博客:Android项目Tab类型主界面大总结 Fragment+TabPageIndicator+ViewPager,有兴趣可以看看。ps:为了代码的简洁,就不添加按钮的点击变化什么的了,主要讲解功能了~~~

5、Fragment家族常用的API

Fragment常用的三个类:

android.app.Fragment 主要用于定义Fragment

android.app.FragmentManager 主要用于在Activity中操作Fragment

android.app.FragmentTransaction 保证一些列Fragment操作的原子性,熟悉事务这个词,一定能明白~

a、获取FragmentManage的方式:

getFragmentManager() // v4中,getSupportFragmentManager

b、主要的操作都是FragmentTransaction的方法

FragmentTransaction transaction = fm.benginTransatcion();//开启一个事务

transaction.add()

往Activity中添加一个Fragment

transaction.remove()

从Activity中移除一个Fragment,如果被移除的Fragment没有添加到回退栈(回退栈后面会详细说),这个Fragment实例将会被销毁。

transaction.replace()

使用另一个Fragment替换当前的,实际上就是remove()然后add()的合体~

transaction.hide()

隐藏当前的Fragment,仅仅是设为不可见,并不会销毁

transaction.show()

显示之前隐藏的Fragment

detach()

会将view从UI中移除,和remove()不同,此时fragment的状态依然由FragmentManager维护。

attach()

重建view视图,附加到UI上并显示。

transatcion.commit()//提交一个事务

注意:常用Fragment的哥们,可能会经常遇到这样Activity状态不一致:State loss这样的错误。主要是因为:commit方法一定要在Activity.onSaveInstance()之前调用。

上述,基本是操作Fragment的所有的方式了,在一个事务开启到提交可以进行多个的添加、移除、替换等操作。

值得注意的是:如果你喜欢使用Fragment,一定要清楚这些方法,哪个会销毁视图,哪个会销毁实例,哪个仅仅只是隐藏,这样才能更好的使用它们。

a、比如:我在FragmentA中的EditText填了一些数据,当切换到FragmentB时,如果希望会到A还能看到数据,则适合你的就是hide和show;也就是说,希望保留用户操作的面板,你可以使用hide和show,当然了不要使劲在那new实例,进行下非null判断。

b、再比如:我不希望保留用户操作,你可以使用remove(),然后add();或者使用replace()这个和remove,add是相同的效果。

c、remove和detach有一点细微的区别,在不考虑回退栈的情况下,remove会销毁整个Fragment实例,而detach则只是销毁其视图结构,实例并不会被销毁。那么二者怎么取舍使用呢?如果你的当前Activity一直存在,那么在不希望保留用户操作的时候,你可以优先使用detach。

--------------------------------------------------------------------------------------------------------------------------------------------------------------

1、管理Fragment回退栈

类似与Android系统为Activity维护一个任务栈,我们也可以通过Activity维护一个回退栈来保存每次Fragment事务发生的变化。如果你将Fragment任务添加到回退栈,当用户点击后退按钮时,将看到上一次的保存的Fragment。一旦Fragment完全从后退栈中弹出,用户再次点击后退键,则退出当前Activity。

看这样一个效果图:

点击第一个按钮,切换到第二个界面,点击第二个按钮,切换到第三个界面,然后点击Back键依次回退。这像不像初学Android时的Activity跳转,当然了,这里肯定不是,不然我就跪了。这里是Fragment实现的,用户点击Back,实际是Fragment回退栈不断的弹栈。

如何添加一个Fragment事务到回退栈:

FragmentTransaction.addToBackStack(String)

下面讲解代码:很明显一共是3个Fragment和一个Activity.

先看Activity的布局文件:

[html]view plaincopy
  1. <RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent">
  5. <FrameLayout
  6. android:id="@+id/id_content"
  7. android:layout_width="fill_parent"
  8. android:layout_height="fill_parent">
  9. </FrameLayout>
  10. </RelativeLayout>

不同的Fragment就在这个FrameLayout中显示。

MainActivity.java

[java]view plaincopy
  1. packagecom.zhy.zhy_fragments;
  2. importandroid.app.Activity;
  3. importandroid.app.FragmentManager;
  4. importandroid.app.FragmentTransaction;
  5. importandroid.os.Bundle;
  6. importandroid.view.Window;
  7. publicclassMainActivityextendsActivity
  8. {
  9. @Override
  10. protectedvoidonCreate(BundlesavedInstanceState)
  11. {
  12. super.onCreate(savedInstanceState);
  13. requestWindowFeature(Window.FEATURE_NO_TITLE);
  14. setContentView(R.layout.activity_main);
  15. FragmentManagerfm=getFragmentManager();
  16. FragmentTransactiontx=fm.beginTransaction();
  17. tx.add(R.id.id_content,newFragmentOne(),"ONE");
  18. tx.commit();
  19. }
  20. }

很简单,直接将FragmentOne添加到布局文件中的FrameLayout中,注意这里并没有调用FragmentTransaction.addToBackStack(String),因为我不喜欢在当前显示时,点击Back键出现白板。而是正确的相应Back键,即退出我们的Activity.

下面是FragmentOne

[java]view plaincopy
  1. packagecom.zhy.zhy_fragments;
  2. importandroid.app.Fragment;
  3. importandroid.app.FragmentManager;
  4. importandroid.app.FragmentTransaction;
  5. importandroid.os.Bundle;
  6. importandroid.view.LayoutInflater;
  7. importandroid.view.View;
  8. importandroid.view.View.OnClickListener;
  9. importandroid.view.ViewGroup;
  10. importandroid.widget.Button;
  11. publicclassFragmentOneextendsFragmentimplementsOnClickListener
  12. {
  13. privateButtonmBtn;
  14. @Override
  15. publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,
  16. BundlesavedInstanceState)
  17. {
  18. Viewview=inflater.inflate(R.layout.fragment_one,container,false);
  19. mBtn=(Button)view.findViewById(R.id.id_fragment_one_btn);
  20. mBtn.setOnClickListener(this);
  21. returnview;
  22. }
  23. @Override
  24. publicvoidonClick(Viewv)
  25. {
  26. FragmentTwofTwo=newFragmentTwo();
  27. FragmentManagerfm=getFragmentManager();
  28. FragmentTransactiontx=fm.beginTransaction();
  29. tx.replace(R.id.id_content,fTwo,"TWO");
  30. tx.addToBackStack(null);
  31. tx.commit();
  32. }
  33. }


我们在点击FragmentOne中的按钮时,使用了replace方法,如果你看了前一篇博客,一定记得replace是remove和add的合体,并且如果不添加事务到回退栈,前一个Fragment实例会被销毁。这里很明显,我们调用tx.addToBackStack(null);将当前的事务添加到了回退栈,所以FragmentOne实例不会被销毁,但是视图层次依然会被销毁,即会调用onDestoryView和onCreateView,证据就是:仔细看上面的效果图,我们在跳转前在文本框输入的内容,在用户Back得到第一个界面的时候不见了。

接下来FragmentTwo

[java]view plaincopy
  1. packagecom.zhy.zhy_fragments;
  2. importandroid.app.Fragment;
  3. importandroid.app.FragmentManager;
  4. importandroid.app.FragmentTransaction;
  5. importandroid.os.Bundle;
  6. importandroid.view.LayoutInflater;
  7. importandroid.view.View;
  8. importandroid.view.View.OnClickListener;
  9. importandroid.view.ViewGroup;
  10. importandroid.widget.Button;
  11. publicclassFragmentTwoextendsFragmentimplementsOnClickListener
  12. {
  13. privateButtonmBtn;
  14. @Override
  15. publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,
  16. BundlesavedInstanceState)
  17. {
  18. Viewview=inflater.inflate(R.layout.fragment_two,container,false);
  19. mBtn=(Button)view.findViewById(R.id.id_fragment_two_btn);
  20. mBtn.setOnClickListener(this);
  21. returnview;
  22. }
  23. @Override
  24. publicvoidonClick(Viewv)
  25. {
  26. FragmentThreefThree=newFragmentThree();
  27. FragmentManagerfm=getFragmentManager();
  28. FragmentTransactiontx=fm.beginTransaction();
  29. tx.hide(this);
  30. tx.add(R.id.id_content,fThree,"THREE");
  31. //tx.replace(R.id.id_content,fThree,"THREE");
  32. tx.addToBackStack(null);
  33. tx.commit();
  34. }
  35. }


这里点击时,我们没有使用replace,而是先隐藏了当前的Fragment,然后添加了FragmentThree的实例,最后将事务添加到回退栈。这样做的目的是为了给大家提供一种方案:如果不希望视图重绘该怎么做,请再次仔细看效果图,我们在FragmentTwo的EditText填写的内容,用户Back回来时,数据还在~~~

最后FragmentThree就是简单的Toast了:

[java]view plaincopy
  1. packagecom.zhy.zhy_fragments;
  2. importandroid.app.Fragment;
  3. importandroid.os.Bundle;
  4. importandroid.view.LayoutInflater;
  5. importandroid.view.View;
  6. importandroid.view.View.OnClickListener;
  7. importandroid.view.ViewGroup;
  8. importandroid.widget.Button;
  9. importandroid.widget.Toast;
  10. publicclassFragmentThreeextendsFragmentimplementsOnClickListener
  11. {
  12. privateButtonmBtn;
  13. @Override
  14. publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,
  15. BundlesavedInstanceState)
  16. {
  17. Viewview=inflater.inflate(R.layout.fragment_three,container,false);
  18. mBtn=(Button)view.findViewById(R.id.id_fragment_three_btn);
  19. mBtn.setOnClickListener(this);
  20. returnview;
  21. }
  22. @Override
  23. publicvoidonClick(Viewv)
  24. {
  25. Toast.makeText(getActivity(),"iamabtninFragmentthree",
  26. Toast.LENGTH_SHORT).show();
  27. }
  28. }


好了,经过上面的介绍,应该已经知道Fragment回退栈是怎么一回事了,以及hide,replace等各自的应用的场景。

这里极其注意一点:上面的整体代码不具有任何参考价值,纯粹为了显示回退栈,在后面讲解了Fragment与Activity通信以后,会重构上面的代码!

2、Fragment与Activity通信

因为所有的Fragment都是依附于Activity的,所以通信起来并不复杂,大概归纳为:

a、如果你Activity中包含自己管理的Fragment的引用,可以通过引用直接访问所有的Fragment的public方法

b、如果Activity中未保存任何Fragment的引用,那么没关系,每个Fragment都有一个唯一的TAG或者ID,可以通过getFragmentManager.findFragmentByTag()或者findFragmentById()获得任何Fragment实例,然后进行操作。

c、在Fragment中可以通过getActivity得到当前绑定的Activity的实例,然后进行操作。

注:如果在Fragment中需要Context,可以通过调用getActivity(),如果该Context需要在Activity被销毁后还存在,则使用getActivity().getApplicationContext()。

3、Fragment与Activity通信的最佳实践

因为要考虑Fragment的重复使用,所以必须降低Fragment与Activity的耦合,而且Fragment更不应该直接操作别的Fragment,毕竟Fragment操作应该由它的管理者Activity来决定。

下面我通过两种方式的代码,分别重构,FragmentOne和FragmentTwo的点击事件,以及Activity对点击事件的响应:

首先看FragmentOne

[java]view plaincopy
  1. packagecom.zhy.zhy_fragments;
  2. importandroid.app.Fragment;
  3. importandroid.os.Bundle;
  4. importandroid.view.LayoutInflater;
  5. importandroid.view.View;
  6. importandroid.view.View.OnClickListener;
  7. importandroid.view.ViewGroup;
  8. importandroid.widget.Button;
  9. publicclassFragmentOneextendsFragmentimplementsOnClickListener
  10. {
  11. privateButtonmBtn;
  12. /**
  13. *设置按钮点击的回调
  14. *@authorzhy
  15. *
  16. */
  17. publicinterfaceFOneBtnClickListener
  18. {
  19. voidonFOneBtnClick();
  20. }
  21. @Override
  22. publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,
  23. BundlesavedInstanceState)
  24. {
  25. Viewview=inflater.inflate(R.layout.fragment_one,container,false);
  26. mBtn=(Button)view.findViewById(R.id.id_fragment_one_btn);
  27. mBtn.setOnClickListener(this);
  28. returnview;
  29. }
  30. /**
  31. *交给宿主Activity处理,如果它希望处理
  32. */
  33. @Override
  34. publicvoidonClick(Viewv)
  35. {
  36. if(getActivity()instanceofFOneBtnClickListener)
  37. {
  38. ((FOneBtnClickListener)getActivity()).onFOneBtnClick();
  39. }
  40. }
  41. }


可以看到现在的FragmentOne不和任何Activity耦合,任何Activity都可以使用;并且我们声明了一个接口,来回调其点击事件,想要管理其点击事件的Activity实现此接口就即可。可以看到我们在onClick中首先判断了当前绑定的Activity是否实现了该接口,如果实现了则调用。

再看FragmentTwo

[java]view plaincopy
  1. packagecom.zhy.zhy_fragments;
  2. importandroid.app.Fragment;
  3. importandroid.os.Bundle;
  4. importandroid.view.LayoutInflater;
  5. importandroid.view.View;
  6. importandroid.view.View.OnClickListener;
  7. importandroid.view.ViewGroup;
  8. importandroid.widget.Button;
  9. publicclassFragmentTwoextendsFragmentimplementsOnClickListener
  10. {
  11. privateButtonmBtn;
  12. privateFTwoBtnClickListenerfTwoBtnClickListener;
  13. publicinterfaceFTwoBtnClickListener
  14. {
  15. voidonFTwoBtnClick();
  16. }
  17. //设置回调接口
  18. publicvoidsetfTwoBtnClickListener(FTwoBtnClickListenerfTwoBtnClickListener)
  19. {
  20. this.fTwoBtnClickListener=fTwoBtnClickListener;
  21. }
  22. @Override
  23. publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,
  24. BundlesavedInstanceState)
  25. {
  26. Viewview=inflater.inflate(R.layout.fragment_two,container,false);
  27. mBtn=(Button)view.findViewById(R.id.id_fragment_two_btn);
  28. mBtn.setOnClickListener(this);
  29. returnview;
  30. }
  31. @Override
  32. publicvoidonClick(Viewv)
  33. {
  34. if(fTwoBtnClickListener!=null)
  35. {
  36. fTwoBtnClickListener.onFTwoBtnClick();
  37. }
  38. }
  39. }


与FragmentOne极其类似,但是我们提供了setListener这样的方法,意味着Activity不仅需要实现该接口,还必须显示调用mFTwo.setfTwoBtnClickListener(this)。

最后看Activity :

[java]view plaincopy
  1. packagecom.zhy.zhy_fragments;
  2. importandroid.app.Activity;
  3. importandroid.app.FragmentManager;
  4. importandroid.app.FragmentTransaction;
  5. importandroid.os.Bundle;
  6. importandroid.view.Window;
  7. importcom.zhy.zhy_fragments.FragmentOne.FOneBtnClickListener;
  8. importcom.zhy.zhy_fragments.FragmentTwo.FTwoBtnClickListener;
  9. publicclassMainActivityextendsActivityimplementsFOneBtnClickListener,
  10. FTwoBtnClickListener
  11. {
  12. privateFragmentOnemFOne;
  13. privateFragmentTwomFTwo;
  14. privateFragmentThreemFThree;
  15. @Override
  16. protectedvoidonCreate(BundlesavedInstanceState)
  17. {
  18. super.onCreate(savedInstanceState);
  19. requestWindowFeature(Window.FEATURE_NO_TITLE);
  20. setContentView(R.layout.activity_main);
  21. mFOne=newFragmentOne();
  22. FragmentManagerfm=getFragmentManager();
  23. FragmentTransactiontx=fm.beginTransaction();
  24. tx.add(R.id.id_content,mFOne,"ONE");
  25. tx.commit();
  26. }
  27. /**
  28. *FragmentOne按钮点击时的回调
  29. */
  30. @Override
  31. publicvoidonFOneBtnClick()
  32. {
  33. if(mFTwo==null)
  34. {
  35. mFTwo=newFragmentTwo();
  36. mFTwo.setfTwoBtnClickListener(this);
  37. }
  38. FragmentManagerfm=getFragmentManager();
  39. FragmentTransactiontx=fm.beginTransaction();
  40. tx.replace(R.id.id_content,mFTwo,"TWO");
  41. tx.addToBackStack(null);
  42. tx.commit();
  43. }
  44. /**
  45. *FragmentTwo按钮点击时的回调
  46. */
  47. @Override
  48. publicvoidonFTwoBtnClick()
  49. {
  50. if(mFThree==null)
  51. {
  52. mFThree=newFragmentThree();
  53. }
  54. FragmentManagerfm=getFragmentManager();
  55. FragmentTransactiontx=fm.beginTransaction();
  56. tx.hide(mFTwo);
  57. tx.add(R.id.id_content,mFThree,"THREE");
  58. //tx.replace(R.id.id_content,fThree,"THREE");
  59. tx.addToBackStack(null);
  60. tx.commit();
  61. }
  62. }


代码重构结束,与开始的效果一模一样。上面两种通信方式都是值得推荐的,随便选择一种自己喜欢的。这里再提一下:虽然Fragment和Activity可以通过getActivity与findFragmentByTag或者findFragmentById,进行任何操作,甚至在Fragment里面操作另外的Fragment,但是没有特殊理由是绝对不提倡的。Activity担任的是Fragment间类似总线一样的角色,应当由它决定Fragment如何操作。另外虽然Fragment不能响应Intent打开,但是Activity可以,Activity可以接收Intent,然后根据参数判断显示哪个Fragment。

4、如何处理运行时配置发生变化

运行时配置发生变化,最常见的就是屏幕发生旋转,如果你不知道如何处理屏幕变化可以参考:Android 屏幕旋转 处理 AsyncTask 和 ProgressDialog 的最佳方案

这里提一下:很多人觉得强制设置屏幕的方向就可以了,但是有一点,当你的应用被至于后台(例如用户点击了home),长时间没有返回的时候,你的应用也会被重新启动。比如上例:如果你把上面的例子你至于FragmentThree界面,然后处于后台状态,长时间后你会发现当你再次通过home打开时,上面FragmentThree与FragmentOne叠加在一起,这就是因为你的Activity重新启动,在原来的FragmentThree上又绘制了一个FragmentOne。

好了,下面看一段代码:

Activity:

[java]view plaincopy
  1. packagecom.zhy.zhy_fragments;
  2. importandroid.app.Activity;
  3. importandroid.app.FragmentManager;
  4. importandroid.app.FragmentTransaction;
  5. importandroid.os.Bundle;
  6. importandroid.view.Window;
  7. publicclassMainActivityextendsActivity
  8. {
  9. privateFragmentOnemFOne;
  10. @Override
  11. protectedvoidonCreate(BundlesavedInstanceState)
  12. {
  13. super.onCreate(savedInstanceState);
  14. requestWindowFeature(Window.FEATURE_NO_TITLE);
  15. setContentView(R.layout.activity_main);
  16. mFOne=newFragmentOne();
  17. FragmentManagerfm=getFragmentManager();
  18. FragmentTransactiontx=fm.beginTransaction();
  19. tx.add(R.id.id_content,mFOne,"ONE");
  20. tx.commit();
  21. }
  22. }


Fragment

[java]view plaincopy
  1. packagecom.zhy.zhy_fragments;
  2. importandroid.app.Fragment;
  3. importandroid.os.Bundle;
  4. importandroid.util.Log;
  5. importandroid.view.LayoutInflater;
  6. importandroid.view.View;
  7. importandroid.view.ViewGroup;
  8. publicclassFragmentOneextendsFragment
  9. {
  10. privatestaticfinalStringTAG="FragmentOne";
  11. @Override
  12. publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,
  13. BundlesavedInstanceState)
  14. {
  15. Log.e(TAG,"onCreateView");
  16. Viewview=inflater.inflate(R.layout.fragment_one,container,false);
  17. returnview;
  18. }
  19. @Override
  20. publicvoidonCreate(BundlesavedInstanceState)
  21. {
  22. //TODOAuto-generatedmethodstub
  23. super.onCreate(savedInstanceState);
  24. Log.e(TAG,"onCreate");
  25. }
  26. @Override
  27. publicvoidonDestroyView()
  28. {
  29. //TODOAuto-generatedmethodstub
  30. super.onDestroyView();
  31. Log.e(TAG,"onDestroyView");
  32. }
  33. @Override
  34. publicvoidonDestroy()
  35. {
  36. //TODOAuto-generatedmethodstub
  37. super.onDestroy();
  38. Log.e(TAG,"onDestroy");
  39. }
  40. }


很简单的代码,当你运行之后,不断的旋转屏幕,你会发现每旋转一次屏幕,屏幕上就多了一个FragmentOne的实例,并且后台log会打印出许多套生命周期的回调。

类似:

[html]view plaincopy
  1. 07-2008:18:46.651:E/FragmentOne(1633):onCreate
  2. 07-2008:18:46.651:E/FragmentOne(1633):onCreate
  3. 07-2008:18:46.651:E/FragmentOne(1633):onCreate
  4. 07-2008:18:46.681:E/FragmentOne(1633):onCreateView
  5. 07-2008:18:46.831:E/FragmentOne(1633):onCreateView
  6. 07-2008:18:46.891:E/FragmentOne(1633):onCreateView


这是为什么呢,因为当屏幕发生旋转,Activity发生重新启动,默认的Activity中的Fragment也会跟着Activity重新创建;这样造成当旋转的时候,本身存在的Fragment会重新启动,然后当执行Activity的onCreate时,又会再次实例化一个新的Fragment,这就是出现的原因。

那么如何解决呢:

其实通过检查onCreate的参数Bundle savedInstanceState就可以判断,当前是否发生Activity的重新创建:

默认的savedInstanceState会存储一些数据,包括Fragment的实例:通过打印可以看出:

[java]view plaincopy
  1. 07-2008:23:12.952:E/FragmentOne(1782):Bundle[{android:fragments=android.app.FragmentManagerState@40d0b7b8,android:viewHierarchyState=Bundle[{android:focusedViewId=2131230721,android:views=android.util.SparseArray@40d0af68}]}]

所以,我们简单改一下代码,只有在savedInstanceState==null时,才进行创建Fragment实例:

[java]view plaincopy
  1. packagecom.zhy.zhy_fragments;
  2. importandroid.app.Activity;
  3. importandroid.app.FragmentManager;
  4. importandroid.app.FragmentTransaction;
  5. importandroid.os.Bundle;
  6. importandroid.util.Log;
  7. importandroid.view.Window;
  8. publicclassMainActivityextendsActivity
  9. {
  10. privatestaticfinalStringTAG="FragmentOne";
  11. privateFragmentOnemFOne;
  12. @Override
  13. protectedvoidonCreate(BundlesavedInstanceState)
  14. {
  15. super.onCreate(savedInstanceState);
  16. requestWindowFeature(Window.FEATURE_NO_TITLE);
  17. setContentView(R.layout.activity_main);
  18. Log.e(TAG,savedInstanceState+"");
  19. if(savedInstanceState==null)
  20. {
  21. mFOne=newFragmentOne();
  22. FragmentManagerfm=getFragmentManager();
  23. FragmentTransactiontx=fm.beginTransaction();
  24. tx.add(R.id.id_content,mFOne,"ONE");
  25. tx.commit();
  26. }
  27. }
  28. }


现在无论进行多次旋转都只会有一个Fragment实例在Activity中。

现在还存在一个问题,就是重新绘制时,Fragment发生重建,原本的数据如何保持?

其实和Activity类似,Fragment也有onSaveInstanceState的方法,在此方法中进行保存数据,然后在onCreate或者onCreateView或者onActivityCreated进行恢复都可以。

由于篇幅原因,就不贴测试代码了。

5、Fragmeny与ActionBar和MenuItem集成

Fragment可以添加自己的MenuItem到Activity的ActionBar或者可选菜单中。

a、在Fragment的onCreate中调用 setHasOptionsMenu(true);

b、然后在Fragment子类中实现onCreateOptionsMenu

c、如果希望在Fragment中处理MenuItem的点击,也可以实现onOptionsItemSelected;当然了Activity也可以直接处理该MenuItem的点击事件。

代码:

Fragment

[java]view plaincopy
  1. packagecom.zhy.zhy_fragments;
  2. importandroid.app.Fragment;
  3. importandroid.os.Bundle;
  4. importandroid.view.LayoutInflater;
  5. importandroid.view.Menu;
  6. importandroid.view.MenuInflater;
  7. importandroid.view.MenuItem;
  8. importandroid.view.View;
  9. importandroid.view.ViewGroup;
  10. importandroid.widget.Toast;
  11. publicclassFragmentOneextendsFragment
  12. {
  13. @Override
  14. publicvoidonCreate(BundlesavedInstanceState)
  15. {
  16. super.onCreate(savedInstanceState);
  17. setHasOptionsMenu(true);
  18. }
  19. @Override
  20. publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,
  21. BundlesavedInstanceState)
  22. {
  23. Viewview=inflater.inflate(R.layout.fragment_one,container,false);
  24. returnview;
  25. }
  26. @Override
  27. publicvoidonCreateOptionsMenu(Menumenu,MenuInflaterinflater)
  28. {
  29. inflater.inflate(R.menu.fragment_menu,menu);
  30. }
  31. @Override
  32. publicbooleanonOptionsItemSelected(MenuItemitem)
  33. {
  34. switch(item.getItemId())
  35. {
  36. caseR.id.id_menu_fra_test:
  37. Toast.makeText(getActivity(),"FragmentMenuItem1",Toast.LENGTH_SHORT).show();
  38. break;
  39. }
  40. returntrue;
  41. }
  42. }


Activity

[java]view plaincopy
  1. packagecom.zhy.zhy_fragments;
  2. importandroid.app.Activity;
  3. importandroid.app.FragmentManager;
  4. importandroid.app.FragmentTransaction;
  5. importandroid.os.Bundle;
  6. importandroid.util.Log;
  7. importandroid.view.Menu;
  8. importandroid.view.MenuItem;
  9. importandroid.view.Window;
  10. importandroid.widget.Toast;
  11. publicclassMainActivityextendsActivity
  12. {
  13. privatestaticfinalStringTAG="FragmentOne";
  14. privateFragmentOnemFOne;
  15. @Override
  16. protectedvoidonCreate(BundlesavedInstanceState)
  17. {
  18. super.onCreate(savedInstanceState);
  19. requestWindowFeature(Window.FEATURE_NO_TITLE);
  20. setContentView(R.layout.activity_main);
  21. Log.e(TAG,savedInstanceState+"");
  22. if(savedInstanceState==null)
  23. {
  24. mFOne=newFragmentOne();
  25. FragmentManagerfm=getFragmentManager();
  26. FragmentTransactiontx=fm.beginTransaction();
  27. tx.add(R.id.id_content,mFOne,"ONE");
  28. tx.commit();
  29. }
  30. }
  31. @Override
  32. publicbooleanonCreateOptionsMenu(Menumenu)
  33. {
  34. super.onCreateOptionsMenu(menu);
  35. getMenuInflater().inflate(R.menu.main,menu);
  36. returntrue;
  37. }
  38. @Override
  39. publicbooleanonOptionsItemSelected(MenuItemitem)
  40. {
  41. switch(item.getItemId())
  42. {
  43. caseR.id.action_settings:
  44. Toast.makeText(this,"setting",Toast.LENGTH_SHORT).show();
  45. returntrue;
  46. default:
  47. //如果希望Fragment自己处理MenuItem点击事件,一定不要忘了调用super.xxx
  48. returnsuper.onOptionsItemSelected(item);
  49. }
  50. }
  51. }


效果图:

好了,可以很好的看到,Fragment可以添加MenuItem,也可以自己处理点击~~~

6、没有布局的Fragment的作用

没有布局文件Fragment实际上是为了保存,当Activity重启时,保存大量数据准备的

请参考博客:Android 屏幕旋转 处理 AsyncTask 和 ProgressDialog 的最佳方案

7、使用Fragment创建对话框

这是Google推荐的方式,我也单独写过博客介绍,请参考:Android 官方推荐 : DialogFragment 创建对话框

优质内容筛选与推荐>>
1、Press C#使用指定打印机打印Word,Excel等Office文件和打印PDF文件的代码 (转)
2、HTML总结
3、PKCS 发布的15 个标准与X509
4、echarts整理
5、Activity 工作流配置


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn