Fragment是Android honeycomb 3.0新增的概念,F(xiàn)ragment名為碎片不過卻和Activity十分相似,下面Android123介紹下Android Fragment的作用和用法。Fragment用來描述一些行為或一部分用戶界面在一個Activity中,你可以合并多個fragment在一個單獨的activity中建立多個UI面板,同時重用fragment在多個activity中.你可以認為fragment作為一個activity中的一節(jié)模塊 ,fragment有自己的生命周期,接收自己的輸入事件,你可以添加或移除從運行中的activity. 一個fragment必須總是嵌入在一個activity中,同時fragment的生命周期受activity而影響,舉個例子吧,當activity暫停,那么所有在這個activity的fragments將被destroy釋放。然而當一個activity在運行比如resume時,你可以單獨的操控每個fragment,比如添加或刪除。 Fragment作為Android 3.0的新特性,有些功能還是比較強大的,比如 合并兩個Activity,如圖 我們可以看到兩個Activity通過兩個Fragment合并到一個Activity的布局方式,對于平板等大屏幕設(shè)備來說有著不錯的展示面板。不過因為Fragment和Activity的生命周期都比較復(fù)雜,我們分別對比下:
創(chuàng)建一個fragment你必須創(chuàng)建一個Fragment的子類或存在的子類,比如類似下面的代碼 public static class Android123Fragment extends Fragment {@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.android123_fragment, container, false); } } Fragment類的一些代碼看起來有些像Activity為了讓大家了解清楚,Android開發(fā)網(wǎng)給大家整理下Fragment的生命周期如上圖所示,部分類似Activity的,我們詳細解釋 onCreate() onCreateView() 那么如何添加一個Fragment到Activity中呢? Activity的布局可以這樣寫 <?xml version="1.0" encoding="utf-8"?> 當然有關(guān)Android Fragment的內(nèi)容由于篇幅的原因,Android123將在明天繼續(xù)幫大家分析下,最后提醒大家Fragment存在于Activity的ViewGroup中,按照繼承關(guān)系大家就可以了解他的結(jié)構(gòu),由于Android 3.0的代碼還沒有開源,所以測試只能從Android honeycomb版本的模擬器上進行了。 |
|