1. 程式人生 > >Android Fragment 真正的完全解析(上)

Android Fragment 真正的完全解析(上)

watermark 展示 near 主界面 ddt comm 講解 超級 pro

版權聲明:本文為博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/lmj623565791/article/details/37970961

轉載請標明出處: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的生命周期。官網這張圖很好的說明了兩者生命周期的關系:

技術分享圖片

可以看到Fragment比Activity多了幾個額外的生命周期回調方法:
onAttach(Activity)
當Fragment與Activity發生關聯時調用。
onCreateView(LayoutInflater, ViewGroup,Bundle)
創建該Fragment的視圖
onActivityCreated(Bundle)
當Activity的onCreate方法返回時調用
onDestoryView()
與onCreateView想對應,當該Fragment的視圖被移除時調用
onDetach()
與onAttach相對應,當Fragment與Activity關聯被取消時調用
註意:除了onCreateView,其他的所有方法如果你重寫了,必須調用父類對於該方法的實現,
3、靜態的使用Fragment

嘿嘿,終於到使用的時刻了~~

這是使用Fragment最簡單的一種方式,把Fragment當成普通的控件,直接寫在Activity的布局文件中。步驟:

1、繼承Fragment,重寫onCreateView決定Fragemnt的布局

2、在Activity中聲明此Fragment,就當和普通的View一樣

下面展示一個例子(我使用2個Fragment作為Activity的布局,一個Fragment用於標題布局,一個Fragment用於內容布局):

TitleFragment的布局文件:

  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="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

  1. package com.zhy.zhy_fragments;
  2. import android.app.Fragment;
  3. import android.os.Bundle;
  4. import android.view.LayoutInflater;
  5. import android.view.View;
  6. import android.view.View.OnClickListener;
  7. import android.view.ViewGroup;
  8. import android.widget.ImageButton;
  9. import android.widget.Toast;
  10. public class TitleFragment extends Fragment
  11. {
  12. private ImageButton mLeftMenu;
  13. @Override
  14. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  15. Bundle savedInstanceState)
  16. {
  17. View view = inflater.inflate(R.layout.fragment_title, container, false);
  18. mLeftMenu = (ImageButton) view.findViewById(R.id.id_title_left_btn);
  19. mLeftMenu.setOnClickListener(new OnClickListener()
  20. {
  21. @Override
  22. public void onClick(View v)
  23. {
  24. Toast.makeText(getActivity(),
  25. "i am an ImageButton in TitleFragment ! ",
  26. Toast.LENGTH_SHORT).show();
  27. }
  28. });
  29. return view;
  30. }
  31. }

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

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns: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>

  1. package com.zhy.zhy_fragments;
  2. import android.app.Fragment;
  3. import android.os.Bundle;
  4. import android.view.LayoutInflater;
  5. import android.view.View;
  6. import android.view.ViewGroup;
  7. public class ContentFragment extends Fragment
  8. {
  9. @Override
  10. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  11. Bundle savedInstanceState)
  12. {
  13. return inflater.inflate(R.layout.fragment_content, container, false);
  14. }
  15. }

MainActivity

  1. package com.zhy.zhy_fragments;
  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. import android.view.Window;
  5. public class MainActivity extends Activity
  6. {
  7. @Override
  8. protected void onCreate(Bundle savedInstanceState)
  9. {
  10. super.onCreate(savedInstanceState);
  11. requestWindowFeature(Window.FEATURE_NO_TITLE);
  12. setContentView(R.layout.activity_main);
  13. }
  14. }

Activity的布局文件:

  1. <RelativeLayout xmlns: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,下面添加四個按鈕~~~嘿嘿~~不是微信的按鈕- -!

  1. <RelativeLayout xmlns: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

  1. package com.zhy.zhy_fragments;
  2. import android.app.Activity;
  3. import android.app.FragmentManager;
  4. import android.app.FragmentTransaction;
  5. import android.os.Bundle;
  6. import android.view.View;
  7. import android.view.View.OnClickListener;
  8. import android.view.Window;
  9. import android.widget.LinearLayout;
  10. public class MainActivity extends Activity implements OnClickListener
  11. {
  12. private LinearLayout mTabWeixin;
  13. private LinearLayout mTabFriend;
  14. private ContentFragment mWeixin;
  15. private FriendFragment mFriend;
  16. @Override
  17. protected void onCreate(Bundle savedInstanceState)
  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. private void setDefaultFragment()
  31. {
  32. FragmentManager fm = getFragmentManager();
  33. FragmentTransaction transaction = fm.beginTransaction();
  34. mWeixin = new ContentFragment();
  35. transaction.replace(R.id.id_content, mWeixin);
  36. transaction.commit();
  37. }
  38. @Override
  39. public void onClick(View v)
  40. {
  41. FragmentManager fm = getFragmentManager();
  42. // 開啟Fragment事務
  43. FragmentTransaction transaction = fm.beginTransaction();
  44. switch (v.getId())
  45. {
  46. case R.id.tab_bottom_weixin:
  47. if (mWeixin == null)
  48. {
  49. mWeixin = new ContentFragment();
  50. }
  51. // 使用當前Fragment的布局替代id_content的控件
  52. transaction.replace(R.id.id_content, mWeixin);
  53. break;
  54. case R.id.tab_bottom_friend:
  55. if (mFriend == null)
  56. {
  57. mFriend = new FriendFragment();
  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其實類似:

  1. package com.zhy.zhy_fragments;
  2. import android.app.Fragment;
  3. import android.os.Bundle;
  4. import android.view.LayoutInflater;
  5. import android.view.View;
  6. import android.view.ViewGroup;
  7. public class FriendFragment extends Fragment
  8. {
  9. @Override
  10. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  11. Bundle savedInstanceState)
  12. {
  13. return inflater.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。

上述已經介紹完成了Fragment常用的一些方法,相信看完,大家一定清楚了Fragment的產生理由,以及如何使用Fragment,再根據API的講解,也能明白,曾經為何覺得Fragment會出現一些列亂七八槽的問題,終究是因為沒有弄清楚其生命周期。

由於篇幅原因,剩下的內容留到下一篇了。在下一篇,會介紹:

1、如何管理Fragment回退棧

2、Fragment如何與Activity交互

3、Fragment與Activity交互的最佳實踐

4、沒有視圖的Fragment的用處

5、使用Fragment創建對話框

6、如何與ActionBar,MenuItem集成等~~

Android Fragment 真正的完全解析(上)