1、什麼是Fragmenthtml
Android在3.0中引入了fragments的概念,主要目的是用在大屏幕設備上--例如平板電腦上,支持更加動態和靈活的UI設計。平板電腦的屏幕要比手機的大得多,有更多的空間來放更多的UI組件,而且這些組件之間會產生更多的交互。Fragment容許這樣的一種設計,而不須要你親自來管理 viewhierarchy的複雜變化。 經過將activity的佈局分散到fragment中, 你能夠在運行時修改activity的外觀,並在由activity管理的back stack中保存那些變化。當一個片斷指定了自身的佈局時,它能和其餘片斷配置成不一樣的組合,在活動中爲不一樣的屏幕尺寸修改佈局配置(小屏幕可能每次顯示一個片斷,而大屏幕則能夠顯示兩個或更多)。java
2、誰在使用Fragmentandroid
3、Fragment的優勢和缺點git
與其說是Fragment的缺點,不如說是每一個應用程序模塊之間的通信都面臨地耦合問題github
4、如何使用Fragmentsql
若是你的應用版本在3.0以上,那就直接使用Fragment就能夠了,它在android.app.Fragment這個裏面。若是版本低於3.0,那就須要使用android-support-v4.jar這個jar包了,Android Support Library(支持庫)提供了包含一個API庫的JAR文件,當你的應用運行在Android早期版本時,Support Library(支持庫)容許你的應用使用一些最近版本的Android API。注意:如今建立程序的時候,默認會有android-support-v4.jar這個包,因此若是是3.0以後在繼承Fragment時會有兩個Fragment包,要選擇android.app.Fragment。app
你能夠把fragment看做是activity的模塊化組件,它擁有本身的生命週期,框架
接受它本身的輸入事件,你也能夠在運行activity的時候添加或者移除它(有點像能夠在不一樣的activity中重用的「子activity」)。這節課演示怎麼樣使用Support Library繼承Fragment類,如此你的app(應用)就能與運行android1.6老版本的系統設備兼容 。注意:若是你由於一些其餘緣由決定你的app須要的最低API版本爲11或者更高,那你就不必使用Support Library,而能夠直接使用框架內置的Fragment類和相關API。咱們分別使用來自Support Library的API和內置在平臺(API),使用特定包名下的API跟內置在平臺(API)的仍是略有不一樣。ide
使用Fragment有兩種方式:一是像在佈局文件添加一個控件同樣,在xml裏面聲明一個Fragment就行;例以下面這樣:模塊化
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"> <fragment android:name="com.example.android.fragments.HeadlinesFragment" android:id="@+id/headlines_fragment" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" /> <fragment android:name="com.example.android.fragments.ArticleFragment" android:id="@+id/article_fragment" android:layout_weight="2" android:layout_width="0dp" android:layout_height="match_parent" /> </LinearLayout>
二是在程序裏面動態的建立、刪除、替換等。這個須要使用到事務,相似於sqlitel裏面的事務。
//獲得一個fragment 事務(相似sqlite的操做) FragmentTransaction ft = getFragmentManager() .beginTransaction(); ft.replace(R.id.details, details);//將獲得的fragment 替換當前的viewGroup內容,add則不替換會依次累加 ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);//設置動畫效果 ft.commit();//提交
一、先用第一中方式接受如何使用Fragment。
要建立一個fragment須要繼承Fragment類,而後重寫關鍵的生命週期方法插入你本身的應用邏輯,操做的方式跟建立一個Activity相似。
不一樣的是當你建立一個Fragment時,你必須使用onCreateView()回調去定義你的佈局。事實上,這是惟一的須要讓fragment得到運行的回調函數。例如,這裏有一個簡單的指定了本身佈局的fragment:
import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.ViewGroup; public class ArticleFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.article_view, container, false); } }
就跟activity同樣,fragment也應該要實現其餘的生命週期方法來管理它的狀態,好比當fragment被activity添加或者刪除,當activity生命週期狀態轉換時(相似這種操做都會影響到fragment的狀態)。例如,當activity的onPuase()方法被調用的時候,全部activity中的fragment也都會接收到onPause()方法的調用。
由於fragment是可重用的,模塊化的UI組件,每個Fragment實例必須與父類FragmentActivity相關聯。你能夠經過在你Activity佈局XML文件中定義每個fragment來得到關聯。注意:FragmentActivity是在系統版本低於API level 11時由Support Library提供用來管理fragment的特殊activity。若是你支持的最低系統版本是API level 11或者更高,那你能夠直接使用常規的Activity。如下是一個例子,當設備屏幕被認爲「大」的時候,一個佈局文件添加了兩個fragment到activity。當屏幕比較大的時候(好比平板)是能夠同時顯示兩個fragment的,可是屏幕比較小(好比普通手機)同一時間只能顯示一個fragment,這是因爲它們的屏幕尺寸形成的。這個佈局文件被指定在「高」分辨率的目錄名下。(譯者注:請注意下面xml的目錄結構:是在res目錄下的layout-large目錄下,這樣的目錄下存放的文件一般都是用來支持高分辨率的佈局文件)res/layout-large/news_articles.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"> <fragment android:name="com.example.android.fragments.HeadlinesFragment" android:id="@+id/headlines_fragment" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" /> <fragment android:name="com.example.android.fragments.ArticleFragment" android:id="@+id/article_fragment" android:layout_weight="2" android:layout_width="0dp" android:layout_height="match_parent" /> </LinearLayout>
這裏展現了在activity中怎樣運用這個佈局:
import android.os.Bundle; import android.support.v4.app.FragmentActivity; public class MainActivity extends FragmentActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.news_articles); } }
注意:當你經過在佈局XML文件中定義fragment以達到添加一個fragment到activity中時,你不能在運行時移除此fragment。在Activity中定義了兩個Fragment,一個是放在左邊的LeftFragment,一個是放在右邊的RightFragment.如下是代碼:首先咱們要實現本身的Fragment類。
LeftFragment類:
package com.example.teblets; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class LeftFragment extends Fragment { @Override public void onAttach(Activity activity) { // TODO Auto-generated method stub super.onAttach(activity); System.out.println("LeftFragment onAttach"); } @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); System.out.println("LeftFragment onCreate"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub return inflater.inflate(R.layout.fragment_left, container,true); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); System.out.println("LeftFragment onDestroy"); } @Override public void onDestroyView() { // TODO Auto-generated method stub super.onDestroyView(); System.out.println("LeftFragment onDestroyView"); } @Override public void onPause() { // TODO Auto-generated method stub super.onPause(); System.out.println("LeftFragment onPause"); } @Override public void onResume() { // TODO Auto-generated method stub super.onResume(); System.out.println("LeftFragment onResume"); } @Override public void onStart() { // TODO Auto-generated method stub super.onStart(); System.out.println("LeftFragment onStart"); } @Override public void onStop() { // TODO Auto-generated method stub super.onStop(); System.out.println("LeftFragment onStop"); } }
這裏實現了幾種回調函數,主要是爲了看清Activity和Fragment生命週期之間的 關係.其中onCreateView()方法是將本Fragment對應的佈局返回給Activity的佈局,讓Activity進行加載. inflater.inflate(R.layout.leftfragment, container, true)方法中的第一個參數R.layout.leftfragment是這個Fragment對應的佈局文件ID, 第二個參數container是要插入的目標Activity, 第三個參數是決定這個Fragment是否依附於這個container。
LeftFragment對應的佈局文件:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/holo_orange_dark" android:orientation="vertical" > <Button android:id="@+id/previous_button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/previous_button" /> <Button android:id="@+id/next_button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/next_button" /> <Button android:id="@+id/exit_button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/exit_button" /> </LinearLayout>
RightFragment類:
package com.example.teblets; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class RightFragment extends Fragment { @Override public void onAttach(Activity activity) { // TODO Auto-generated method stub super.onAttach(activity); System.out.println("LeftFragment onAttach"); } @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); System.out.println("LeftFragment onCreate"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub return inflater.inflate(R.layout.fragment_right, container,true); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); System.out.println("LeftFragment onDestroy"); } @Override public void onDestroyView() { // TODO Auto-generated method stub super.onDestroyView(); System.out.println("LeftFragment onDestroyView"); } @Override public void onPause() { // TODO Auto-generated method stub super.onPause(); System.out.println("LeftFragment onPause"); } @Override public void onResume() { // TODO Auto-generated method stub super.onResume(); System.out.println("LeftFragment onResume"); } @Override public void onStart() { // TODO Auto-generated method stub super.onStart(); System.out.println("LeftFragment onStart"); } @Override public void onStop() { // TODO Auto-generated method stub super.onStop(); System.out.println("LeftFragment onStop"); } }
RightFragment對應的佈局文件:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/show_message" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@android:color/holo_blue_dark" android:text="@string/show_message" /> </LinearLayout>
最後是Activity的佈局文件:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:baselineAligned="false" android:orientation="horizontal" > <fragment android:id="@+id/left_fragment" android:name="com.example.teblets.LeftFragment" android:layout_width="match_parent" android:layout_height="fill_parent" android:layout_weight="3" /> <fragment android:id="@+id/right_fragment" android:name="com.example.teblets.RightFragment" android:layout_width="match_parent" android:layout_height="fill_parent" android:layout_weight="1" /> </LinearLayout>
在Activity中的佈局文件中加入Fragment標籤,其中android:name屬性對應的就是自定義Fragment類的全名,系統會根據這個調用指定的Fragment的onCreateView()方法來獲得這個Fragment的佈局,而後加入Activity中. onCreateView()方法中的Container參數就是這時候傳遞過去的。顯示結果:
打開程序時生命週期顯示:
按返回鍵時生命週期顯示:
二、動態使用Fragment
相比上節課提到的使用標籤在佈局文件中爲activity定義一個fragment組件,更好的方式是在activity運行時添加fragment。若是你想在activity的生命週期中變換fragment的話就必須這樣作。執行相似添加或者刪除fragment的事務,你必須使用FragmentManager建立一個FragmentTransaction,它提供了添加,刪除以及其餘fragment事務的API。若是你的activity容許移除或者替換fragment,你應該在activity的onCreate())方法中添加初始化的fragment。在你處理fragment(尤爲是你在運行時添加的那些)的時候,有一個很重要的規則就是你的fragment放置位置的佈局中必須有一個視圖容器。下面這個佈局是上節課在同一時間只顯示一個fragment佈局的替代品。爲了將一個fragment替換成另外一個,這個activity佈局包含了一個空的FrameLayout做爲fragment容器。注意這個文件名跟上節課的佈局文件名字同樣,可是這個佈局並無指定在「高分辨率」目錄中(譯者注:請注意下面xml的路徑,res/layout這個layout文件夾並無像上節課提到的是一個layout-large文件夾),如此這個佈局是用在比large更小的設備屏幕上,由於這個屏幕不能在同一時間充滿兩個fragment。res/layout/news_articles.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" />
在你的activity中,使用Support LibraryAPI,調用getSupportFragmentManager()能夠獲得一個FragmentManager對象,以後調用beginTransaction去建立一個FragmentTransaction對象,再調用add()方法便可添加一個fragment。
你能夠對activity使用同一個FragmentTransaction對象去執行多個fragment事務,當你肯定要作這些操做時,你必須調用 commit()方法。
例如,如下代碼演示怎樣添加一個fragment到前面的layout:
import android.os.Bundle; import android.support.v4.app.FragmentActivity; public class MainActivity extends FragmentActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.news_articles); // Check that the activity is using the layout version with // the fragment_container FrameLayout if (findViewById(R.id.fragment_container) != null) { // However, if we're being restored from a previous state, // then we don't need to do anything and should return or else // we could end up with overlapping fragments. if (savedInstanceState != null) { return; } // Create an instance of ExampleFragment HeadlinesFragment firstFragment = new HeadlinesFragment(); // In case this activity was started with special instructions from an Intent, // pass the Intent's extras to the fragment as arguments firstFragment.setArguments(getIntent().getExtras()); // Add the fragment to the 'fragment_container' FrameLayout getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container, firstFragment).commit(); } } }
因爲fragment是在運行時添加到FrameLayout,而不是直接使用標籤訂義在activity的佈局中,activity能夠移除它或者使用另一個不一樣的fragment替換它。替換一個fragment的過程跟添加差很少,可是須要的是 replace()方法,而不是 add()方法。
須要注意的是,當你執行fragment事務時,好比替換或者刪除一個fragment。容許用戶「後退」或者「撤銷」改變一般是比較合適的作法。爲了讓用戶能夠經過fragment事務「後退」,你必須在你提交fragment事務以前調用 addToBackStack()方法。當你移除或者替換fragment且將事務添加到堆棧中時,被移除的fragment是被中止了(沒有消亡)。若是用戶導航回來從新加載這個fragment,它將會從新啓動;若是你沒有把事務加入到堆棧中,當fragment被刪除或者替換時,這個fragment也就消亡了;
如下使用fragment替換另外一個的例子:
// Create fragment and give it an argument specifying the article it should show ArticleFragment newFragment = new ArticleFragment(); Bundle args = new Bundle(); args.putInt(ArticleFragment.ARG_POSITION, position); newFragment.setArguments(args); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack so the user can navigate back transaction.replace(R.id.fragment_container, newFragment); transaction.addToBackStack(null); // Commit the transaction transaction.commit();
addToBackStack()方法有一個可選的字符串參數,用來指定事務的惟一名稱。這個名稱不是必須的除非你打算使用 FragmentManager.BackStackEntry API執行更高級的fragment操做。
爲了重用Fragment UI組件,你應該將Fragment創建成徹底獨立,模塊化而且定義了本身佈局和行爲的組件。一旦你定義了這些可重用的Fragment,你能夠經過activity,應用程序邏輯使它們關聯,交互以組成一個總體複合型UI。
一般狀況下,你但願一個Fragment能夠與另外一個交互,好比基於用戶事件去修改內容。全部Fragment到Fragment的交互都是經過相關聯的activity來作的。兩個fragment應該從不直接交互。
爲了容許Fragment與它的activity交互,你能夠在fragment類中定義一個接口而且在activity中實現它。fragment能夠在生命週期中的onAttach()方法獲取接口的實現並調用接口的方法與activity交互。如下是fragment到activity的交互例子:
public class HeadlinesFragment extends ListFragment { OnHeadlineSelectedListener mCallback; // Container Activity must implement this interface public interface OnHeadlineSelectedListener { public void onArticleSelected(int position); } @Override public void onAttach(Activity activity) { super.onAttach(activity); // This makes sure that the container activity has implemented // the callback interface. If not, it throws an exception try { mCallback = (OnHeadlineSelectedListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener"); } } ... }
如今fragment可使用OnHeadlineSelectedListener的實例mCallback調用onArticleSelected()方法(或者其餘接口內的方法)提供信息給activity了。
例如,當用戶點擊list item(list子項)時就會調用下面在fragment的方法。fragment使用回調接口提供事件到父的activity。
@Override public void onListItemClick(ListView l, View v, int position, long id) { // Send the event to the host activity mCallback.onArticleSelected(position); }
爲了接收來自fragment的事件回調,包含fragment的activity(你須要用來與fragment交互的activity)必須實現定義在fragment類中的接口。
例如:下面這個activity就實現了上一例子中的接口:
public static class MainActivity extends Activity implements HeadlinesFragment.OnHeadlineSelectedListener{ ... public void onArticleSelected(Uri articleUri) { // The user selected the headline of an article from the HeadlinesFragment // Do something here to display that article } }
宿主activity可使用findFragmentById()方法獲取Fragment實例,而後直接調用fragment的公共方法提供信息給fragment。
例如,假設在上面顯示的那個activity中可能包含另一個fragment,而且用來顯示由上面那個回調方法返回的數據指定的項目。在這個案例中,這個activity能夠從回調函數中得到信息而且傳遞給其餘顯示項目的fragment:
public static class MainActivity extends Activity implements HeadlinesFragment.OnHeadlineSelectedListener{ ... public void onArticleSelected(int position) { // The user selected the headline of an article from the HeadlinesFragment // Do something here to display that article ArticleFragment articleFrag = (ArticleFragment) getSupportFragmentManager().findFragmentById(R.id.article_fragment); if (articleFrag != null) { // If article frag is available, we're in two-pane layout... // Call a method in the ArticleFragment to update its content articleFrag.updateArticleView(position); } else { // Otherwise, we're in the one-pane layout and must swap frags... // Create fragment and give it an argument for the selected article ArticleFragment newFragment = new ArticleFragment(); Bundle args = new Bundle(); args.putInt(ArticleFragment.ARG_POSITION, position); newFragment.setArguments(args); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack so the user can navigate back transaction.replace(R.id.fragment_container, newFragment); transaction.addToBackStack(null); // Commit the transaction transaction.commit(); } } }
5、應用案例
一、Fragment+FragmentTabHost實現仿新浪微博底部菜單欄:TabHost其實已經被棄用了,這個例子就是用來體現一下Fragment的用法,很簡單在切換TabHost的時候加載Fragment。我的以爲意義不大,還不如那種直接加載Activity,裏面再嵌套Fragment來的實在。
二、經過SlidingMenu+Fragment實現當前最流行的側滑:
三、 基於Android Fragment功能的例子:這個例子Fragment之間的交互沒有使用接口的形式,而是直接調用,這樣作比較方便,可是不規範。
四、Android開發 側邊滑動菜單欄SlidingMenu結合Fragment
五、Implementing ActionBarSherlock Fragment Tabs in Android
6、注意事項
一、若是你想在Fragment 裏面建立menu,則必須在onCreate的時候設置讓它能夠存在optionMenu才能夠建立,代碼爲:
public static class DetailsFragment extends Fragment { @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setHasOptionsMenu(true); } }
二、如何解決模塊之間的通信的耦合問題
1.使用接口,讓Activity扮演管理角色,負責分發消息到該窗口的子View
該方案的缺點
2.使用LocalBroadcastManager + IntentFilter解決不一樣組件通信,Intent負責搭載數據
該方案的缺點
3.EventBus
7、總結概括
Fragment是3.0以後一個很重要的API,要深入理解和掌握。
8、Fragment開源項目
一、https://github.com/johnkil/Android-ProgressFragment
二、Implementing Fragment Tabs in Android
8、Demo下載
9、推薦博客:http://www.vogella.com/articles/AndroidFragments/article.html