五月综合缴情婷婷六月,色94色欧美sute亚洲线路二,日韩制服国产精品一区,色噜噜一区二区三区,香港三级午夜理伦三级三

您現(xiàn)在的位置: 365建站網(wǎng) > 365文章 > 什么是Android Fragment及生命周期/靜態(tài)和動(dòng)態(tài)的使用Fragment

什么是Android Fragment及生命周期/靜態(tài)和動(dòng)態(tài)的使用Fragment

文章來(lái)源:365jz.com     點(diǎn)擊數(shù):241    更新時(shí)間:2017-11-29 12:12   參與評(píng)論

自從Fragment出現(xiàn),曾經(jīng)有段時(shí)間,感覺(jué)大家談什么都能跟Fragment談上關(guān)系,做什么都要問(wèn)下Fragment能實(shí)現(xiàn)不~~~哈哈,是不是有點(diǎn)過(guò)~~~

本篇博客力求為大家說(shuō)明Fragment如何產(chǎn)生,什么是Fragment,F(xiàn)ragment生命周期,如何靜態(tài)和動(dòng)態(tài)的使用Fragment,F(xiàn)ragment回退棧,F(xiàn)ragment事務(wù);以及Fragment的一些特殊用途,例如:沒(méi)有布局的Fragment有何用處?Fragment如何與Activity交互?Fragment如何創(chuàng)建對(duì)話框?Fragment如何與ActionBar集成等等。

1、Fragment的產(chǎn)生與介紹

Android運(yùn)行在各種各樣的設(shè)備中,有小屏幕的手機(jī),超大屏的平板甚至電視。針對(duì)屏幕尺寸的差距,很多情況下,都是先針對(duì)手機(jī)開(kāi)發(fā)一套App,然后拷貝一份,修改布局以適應(yīng)平板神馬超級(jí)大屏的。難道無(wú)法做到一個(gè)App可以同時(shí)適應(yīng)手機(jī)和平板么,當(dāng)然了,必須有啊。Fragment的出現(xiàn)就是為了解決這樣的問(wèn)題。你可以把Fragment當(dāng)成Activity的一個(gè)界面的一個(gè)組成部分,甚至Activity的界面可以完全有不同的Fragment組成,更帥氣的是Fragment擁有自己的生命周期和接收、處理用戶的事件,這樣就不必在Activity寫(xiě)一堆控件的事件處理的代碼了。更為重要的是,你可以動(dòng)態(tài)的添加、替換和移除某個(gè)Fragment。

2、Fragment的生命周期

 

Fragment必須是依存與Activity而存在的,因此Activity的生命周期會(huì)直接影響到Fragment的生命周期。官網(wǎng)這張圖很好的說(shuō)明了兩者生命周期的關(guān)系:

可以看到Fragment比Activity多了幾個(gè)額外的生命周期回調(diào)方法:
onAttach(Activity)
當(dāng)Fragment與Activity發(fā)生關(guān)聯(lián)時(shí)調(diào)用。
onCreateView(LayoutInflater, ViewGroup,Bundle)
創(chuàng)建該Fragment的視圖
onActivityCreated(Bundle)
當(dāng)Activity的onCreate方法返回時(shí)調(diào)用
onDestoryView()
與onCreateView想對(duì)應(yīng),當(dāng)該Fragment的視圖被移除時(shí)調(diào)用
onDetach()
與onAttach相對(duì)應(yīng),當(dāng)Fragment與Activity關(guān)聯(lián)被取消時(shí)調(diào)用
注意:除了onCreateView,其他的所有方法如果你重寫(xiě)了,必須調(diào)用父類對(duì)于該方法的實(shí)現(xiàn),
3、靜態(tài)的使用Fragment

嘿嘿,終于到使用的時(shí)刻了~~

這是使用Fragment最簡(jiǎn)單的一種方式,把Fragment當(dāng)成普通的控件,直接寫(xiě)在Activity的布局文件中。步驟:

1、繼承Fragment,重寫(xiě)onCreateView決定Fragemnt的布局

2、在Activity中聲明此Fragment,就當(dāng)和普通的View一樣

下面展示一個(gè)例子(我使用2個(gè)Fragment作為Activity的布局,一個(gè)Fragment用于標(biāo)題布局,一個(gè)Fragment用于內(nèi)容布局):
TitleFragment的布局文件:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="45dp" 
    android:background="@drawable/title_bar" > 
 
    <ImageButton 
        android:id="@+id/id_title_left_btn" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_centerVertical="true" 
        android:layout_marginLeft="3dp" 
        android:background="@drawable/showleft_selector" /> 
 
    <TextView 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" 
        android:gravity="center" 
        android:text="我不是微信" 
        android:textColor="#fff" 
        android:textSize="20sp" 
        android:textStyle="bold" /> 
 
</RelativeLayout> 


TitleFragment

package com.zhy.zhy_fragments; 
 
import android.app.Fragment; 
import android.os.Bundle; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.ViewGroup; 
import android.widget.ImageButton; 
import android.widget.Toast; 
 
public class TitleFragment extends Fragment 

 
    private ImageButton mLeftMenu; 
 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
            Bundle savedInstanceState) 
    { 
        View view = inflater.inflate(R.layout.fragment_title, container, false); 
        mLeftMenu = (ImageButton) view.findViewById(R.id.id_title_left_btn); 
        mLeftMenu.setOnClickListener(new OnClickListener() 
        { 
            @Override 
            public void onClick(View v) 
            { 
                Toast.makeText(getActivity(), 
                        "i am an ImageButton in TitleFragment ! ", 
                        Toast.LENGTH_SHORT).show(); 
            } 
        }); 
        return view; 
    } 


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

<?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:layout_width="fill_parent" 
        android:layout_height="fill_parent" 
        android:gravity="center" 
        android:text="使用Fragment做主面板" 
        android:textSize="20sp" 
        android:textStyle="bold" /> 
 
</LinearLayout> 

 

package com.zhy.zhy_fragments; 
 
import android.app.Fragment; 
import android.os.Bundle; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
 
public class ContentFragment extends Fragment 

 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
            Bundle savedInstanceState) 
    { 
        return inflater.inflate(R.layout.fragment_content, container, false); 
    } 
 


MainActivity

package com.zhy.zhy_fragments; 
 
import android.app.Activity; 
import android.os.Bundle; 
import android.view.Window; 
 
public class MainActivity extends Activity 

 
    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
        super.onCreate(savedInstanceState); 
        requestWindowFeature(Window.FEATURE_NO_TITLE); 
        setContentView(R.layout.activity_main); 
    } 
 


Activity的布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 
 
    <fragment 
        android:id="@+id/id_fragment_title" 
        android:name="com.zhy.zhy_fragments.TitleFragment" 
        android:layout_width="fill_parent" 
        android:layout_height="45dp" /> 
 
    <fragment 
        android:layout_below="@id/id_fragment_title" 
        android:id="@+id/id_fragment_content" 
        android:name="com.zhy.zhy_fragments.ContentFragment" 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" /> 
 
</RelativeLayout> 


是不是把Fragment當(dāng)成普通的View一樣聲明在Activity的布局文件中,然后所有控件的事件處理等代碼都由各自的Fragment去處理,瞬間覺(jué)得Activity好干凈有木有~~代碼的可讀性、復(fù)用性以及可維護(hù)性是不是瞬間提升了~~~下面看下效果圖:

4、動(dòng)態(tài)的使用Fragment
上面已經(jīng)演示了,最簡(jiǎn)單的使用Fragment的方式~下面介紹如何動(dòng)態(tài)的添加、更新、以及刪除Fragment
為了動(dòng)態(tài)使用Fragment,我們修改一下Actvity的布局文件,中間使用一個(gè)FrameLayout,下面添加四個(gè)按鈕~~~嘿嘿~~不是微信的按鈕- -!

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 
 
    <fragment 
        android:id="@+id/id_fragment_title" 
        android:name="com.zhy.zhy_fragments.TitleFragment" 
        android:layout_width="fill_parent" 
        android:layout_height="45dp" /> 
 
    <include 
        android:id="@+id/id_ly_bottombar" 
        android:layout_width="fill_parent" 
        android:layout_height="55dp" 
        android:layout_alignParentBottom="true" 
        layout="@layout/bottombar" /> 
 
    <FrameLayout 
        android:id="@+id/id_content" 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" 
        android:layout_above="@id/id_ly_bottombar" 
        android:layout_below="@id/id_fragment_title" /> 
 
</RelativeLayout> 


底部四個(gè)按鈕的布局就不貼了,到時(shí)看效果圖就明白了~~
下面主Activity

package com.zhy.zhy_fragments; 
 
import android.app.Activity; 
import android.app.FragmentManager; 
import android.app.FragmentTransaction; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.Window; 
import android.widget.LinearLayout; 
 
public class MainActivity extends Activity implements OnClickListener 

    private LinearLayout mTabWeixin; 
    private LinearLayout mTabFriend; 
 
    private ContentFragment mWeixin; 
    private FriendFragment mFriend; 
 
    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
        super.onCreate(savedInstanceState); 
        requestWindowFeature(Window.FEATURE_NO_TITLE); 
        setContentView(R.layout.activity_main); 
 
        // 初始化控件和聲明事件 
        mTabWeixin = (LinearLayout) findViewById(R.id.tab_bottom_weixin); 
        mTabFriend = (LinearLayout) findViewById(R.id.tab_bottom_friend); 
        mTabWeixin.setOnClickListener(this); 
        mTabFriend.setOnClickListener(this); 
 
        // 設(shè)置默認(rèn)的Fragment 
        setDefaultFragment(); 
    } 
 
    private void setDefaultFragment() 
    { 
        FragmentManager fm = getFragmentManager(); 
        FragmentTransaction transaction = fm.beginTransaction(); 
        mWeixin = new ContentFragment(); 
        transaction.replace(R.id.id_content, mWeixin); 
        transaction.commit(); 
    } 
 
    @Override 
    public void onClick(View v) 
    { 
        FragmentManager fm = getFragmentManager(); 
        // 開(kāi)啟Fragment事務(wù) 
        FragmentTransaction transaction = fm.beginTransaction(); 
 
        switch (v.getId()) 
        { 
        case R.id.tab_bottom_weixin: 
            if (mWeixin == null) 
            { 
                mWeixin = new ContentFragment(); 
            } 
            // 使用當(dāng)前Fragment的布局替代id_content的控件 
            transaction.replace(R.id.id_content, mWeixin); 
            break; 
        case R.id.tab_bottom_friend: 
            if (mFriend == null) 
            { 
                mFriend = new FriendFragment(); 
            } 
            transaction.replace(R.id.id_content, mFriend); 
            break; 
        } 
        // transaction.addToBackStack(); 
        // 事務(wù)提交 
        transaction.commit(); 
    } 
 


可以看到我們使用FragmentManager對(duì)Fragment進(jìn)行了動(dòng)態(tài)的加載,這里使用的是replace方法~~下一節(jié)我會(huì)詳細(xì)介紹FragmentManager的常用API。
注:如果使用Android3.0以下的版本,需要引入v4的包,然后Activity繼承FragmentActivity,然后通過(guò)getSupportFragmentManager獲得FragmentManager。不過(guò)還是建議版Menifest文件的uses-sdk的minSdkVersion和targetSdkVersion都改為11以上,這樣就不必引入v4包了。
代碼中間還有兩個(gè)Fragment的子類,ContentFragment上面已經(jīng)見(jiàn)過(guò),F(xiàn)riendFragment其實(shí)類似:

package com.zhy.zhy_fragments; 
 
import android.app.Fragment; 
import android.os.Bundle; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
 
public class FriendFragment extends Fragment 

 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
            Bundle savedInstanceState) 
    { 
        return inflater.inflate(R.layout.fragment_friend, container, false); 
    } 
 


效果圖:

 

可以看到很好的實(shí)現(xiàn)了效果,其實(shí)這個(gè)效果以前也出現(xiàn)過(guò),地址:Android項(xiàng)目Tab類型主界面大總結(jié) Fragment+TabPageIndicator+ViewPager,有興趣可以看看。ps:為了代碼的簡(jiǎn)潔,就不添加按鈕的點(diǎn)擊變化什么的了,主要講解功能了~~~

5、Fragment家族常用的API

Fragment常用的三個(gè)類:

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

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

android.app.FragmentTransaction 保證一些列Fragment操作的原子性,熟悉事務(wù)這個(gè)詞,一定能明白~

a、獲取FragmentManage的方式:

getFragmentManager() // v4中,getSupportFragmentManager

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

FragmentTransaction transaction = fm.benginTransatcion();//開(kāi)啟一個(gè)事務(wù)

transaction.add() 

往Activity中添加一個(gè)Fragment

transaction.remove()

從Activity中移除一個(gè)Fragment,如果被移除的Fragment沒(méi)有添加到回退棧(回退棧后面會(huì)詳細(xì)說(shuō)),這個(gè)Fragment實(shí)例將會(huì)被銷毀。

transaction.replace()

使用另一個(gè)Fragment替換當(dāng)前的,實(shí)際上就是remove()然后add()的合體~

transaction.hide()

隱藏當(dāng)前的Fragment,僅僅是設(shè)為不可見(jiàn),并不會(huì)銷毀

transaction.show()

顯示之前隱藏的Fragment

detach()

會(huì)將view從UI中移除,和remove()不同,此時(shí)fragment的狀態(tài)依然由FragmentManager維護(hù)。

attach()

重建view視圖,附加到UI上并顯示。

transatcion.commit()//提交一個(gè)事務(wù)

注意:常用Fragment的哥們,可能會(huì)經(jīng)常遇到這樣Activity狀態(tài)不一致:State loss這樣的錯(cuò)誤。主要是因?yàn)椋篶ommit方法一定要在Activity.onSaveInstance()之前調(diào)用。

上述,基本是操作Fragment的所有的方式了,在一個(gè)事務(wù)開(kāi)啟到提交可以進(jìn)行多個(gè)的添加、移除、替換等操作。

值得注意的是:如果你喜歡使用Fragment,一定要清楚這些方法,哪個(gè)會(huì)銷毀視圖,哪個(gè)會(huì)銷毀實(shí)例,哪個(gè)僅僅只是隱藏,這樣才能更好的使用它們。

a、比如:我在FragmentA中的EditText填了一些數(shù)據(jù),當(dāng)切換到FragmentB時(shí),如果希望會(huì)到A還能看到數(shù)據(jù),則適合你的就是hide和show;也就是說(shuō),希望保留用戶操作的面板,你可以使用hide和show,當(dāng)然了不要使勁在那new實(shí)例,進(jìn)行下非null判斷。

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

c、remove和detach有一點(diǎn)細(xì)微的區(qū)別,在不考慮回退棧的情況下,remove會(huì)銷毀整個(gè)Fragment實(shí)例,而detach則只是銷毀其視圖結(jié)構(gòu),實(shí)例并不會(huì)被銷毀。那么二者怎么取舍使用呢?如果你的當(dāng)前Activity一直存在,那么在不希望保留用戶操作的時(shí)候,你可以優(yōu)先使用detach。

 

上述已經(jīng)介紹完成了Fragment常用的一些方法,相信看完,大家一定清楚了Fragment的產(chǎn)生理由,以及如何使用Fragment,再根據(jù)API的講解,也能明白,曾經(jīng)為何覺(jué)得Fragment會(huì)出現(xiàn)一些列亂七八槽的問(wèn)題,終究是因?yàn)闆](méi)有弄清楚其生命周期。

由于篇幅原因,剩下的內(nèi)容留到下一篇了。在下一篇,會(huì)介紹:

1、如何管理Fragment回退棧

2、Fragment如何與Activity交互

3、Fragment與Activity交互的最佳實(shí)踐

4、沒(méi)有視圖的Fragment的用處

5、使用Fragment創(chuàng)建對(duì)話框

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

Android Fragment如何與Activity交互,與ActionBar,MenuItem集成
 

如對(duì)本文有疑問(wèn),請(qǐng)?zhí)峤坏浇涣髡搲?,廣大熱心網(wǎng)友會(huì)為你解答?。?點(diǎn)擊進(jìn)入論壇

發(fā)表評(píng)論 (241人查看,0條評(píng)論)
請(qǐng)自覺(jué)遵守互聯(lián)網(wǎng)相關(guān)的政策法規(guī),嚴(yán)禁發(fā)布色情、暴力、反動(dòng)的言論。
昵稱:
最新評(píng)論
------分隔線----------------------------

其它欄目

· 建站教程
· 365學(xué)習(xí)

業(yè)務(wù)咨詢

· 技術(shù)支持
· 服務(wù)時(shí)間:9:00-18:00
365建站網(wǎng)二維碼

Powered by 365建站網(wǎng) RSS地圖 HTML地圖

copyright © 2013-2024 版權(quán)所有 鄂ICP備17013400號(hào)