天天看點

Fragments的初識---不知道Fragments的不是合格的android開發

http://www.cnblogs.com/meetyourmakers/archive/2011/12/22/2297962.html

fragments是android 3.0 (api level 11)才引入的.但是它卻又是向下相容的.可以支援老的android版本.

隻不過需要導入jar包支援(在這個目錄下:android-sdk-windows\extras\android\support\v4\android-support-v4.jar),

主要用于實作以下這種ui布局

Fragments的初識---不知道Fragments的不是合格的android開發

想要實作這樣一個activity裡面有多個複雜的view布局, 按照以前的慣用寫法可以使用viewgroup 或者自定義一些布局來實作

而fragments就恰恰滿足了我們這一需求,他相比我們原來實作的方法,功能更強大,

簡單說來,我個人覺得可以把fragments看成是一個view,他比view強大的地方是他是有生命周期的 并且這個生命周期會随着他附着的那個activity的改變而改變.

<code>oncreate()</code>the system calls this when creating the

fragment. within your implementation, you should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.

<code>oncreateview()</code>the

system calls this when it's time for the fragment to draw its user interface for the first time. to draw a ui for your fragment, you must return a <code>view</code> from

this method that is the root of your fragment's layout. you can return null if the fragment does not provide a ui.

<code>onpause()</code>the system calls this method as the first indication that

the user is leaving the fragment (though it does not always mean the fragment is being destroyed). this is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back).

這是他的三個主要的方法,或者說生命周期.當他的父activity onpause();的時候,他也會調用onpause();同樣他的父activityonresume();他調用onresume();

這樣就很靈活,比如有大量bitmap的view,就可以在 onpause();釋放掉無用的資源,再在onresume()的時候加載.

這些fragments是由fragmentmanager這樣一個類似棧的容器管理的,可以通過 <code>findfragmentbyid()</code> 或者<code>findfragmentbytag()</code> 找到添加到頁面裡面的fragments.

下面看個小小的demo:

首先我們要寫一個繼承fragment的類,你可以把他看成你的ui界面裡的某一個子產品

Fragments的初識---不知道Fragments的不是合格的android開發
Fragments的初識---不知道Fragments的不是合格的android開發

根據列印輸出,你會發現隻有第一次啟動才會調用oncreateview;而這裡面就是你這個ui子產品的布局

接着是你要展示的activity:

Fragments的初識---不知道Fragments的不是合格的android開發
Fragments的初識---不知道Fragments的不是合格的android開發

然後activity的布局也非常簡單

Fragments的初識---不知道Fragments的不是合格的android開發
Fragments的初識---不知道Fragments的不是合格的android開發

這樣就已經搞定,生成了2個fragment, 這算是靜态的添加吧

如果是動态的添加那就需要用到上面注釋的代碼:

差不多初識就是這樣,希望有人能補充,下個項目有機會一定要嘗試用用

繼續閱讀