Android: Fragment詳解

自從Fragment出現,曾經有段時間,感受你們談什麼都能跟Fragment談上關係,作什麼都要問下Fragment能實現不~哈哈,是否是有點過~
本篇博客力求爲你們說明Fragment如何產生,什麼是Fragment,Fragment生命週期,如何靜態和動態的使用Fragment,Fragment回退棧,Fragment事務;以及Fragment的一些特殊用途,例如:沒有佈局的Fragment有何用處?Fragment如何與Activity交互?Fragment如何建立對話框?Fragment如何與ActionBar集成等等。
一、Fragment的產生與介紹
Android運行在各類各樣的設備中,有小屏幕的手機,超大屏的平板甚至電視。針對屏幕尺寸的差距,不少狀況下,都是先針對手機開發一套App,而後拷貝一份,修改佈局以適應平板神馬超級大屏的。難道沒法作到一個App能夠同時適應手機和平板麼,固然了,必須有啊。Fragment的出現就是爲了解決這樣的問題。你能夠把Fragment當成Activity的一個界面的一個組成部分,甚至Activity的界面能夠徹底有不一樣的Fragment組成,更帥氣的是Fragment擁有本身的生命週期和接收、處理用戶的事件,這樣就沒必要在Activity寫一堆控件的事件處理的代碼了。更爲重要的是,你能夠動態的添加、替換和移除某個Fragment。
二、Fragment的生命週期
Fragment必須是依存與Activity而存在的,所以Activity的生命週期會直接影響到Fragment的生命週期。官網這張圖很好的說明了二者生命週期的關係:
android

能夠看到Fragment比Activity多了幾個額外的生命週期回調方法:
onAttach(Activity)
當Fragment與Activity發生關聯時調用。
onCreateView(LayoutInflater, ViewGroup,Bundle)
建立該Fragment的視圖
onActivityCreated(Bundle)
當Activity的onCreate方法返回時調用
onDestoryView()
與onCreateView想對應,當該Fragment的視圖被移除時調用
onDetach()
與onAttach相對應,當Fragment與Activity關聯被取消時調用
注意:除了onCreateView,其餘的全部方法若是你重寫了,必須調用父類對於該方法的實現,
三、靜態的使用Fragment
嘿嘿,終於到使用的時刻了~~
這是使用Fragment最簡單的一種方式,把Fragment當成普通的控件,直接寫在Activity的佈局文件中。步驟:
一、繼承Fragment,重寫onCreateView決定Fragemnt的佈局
二、在Activity中聲明此Fragment,就當和普通的View同樣
下面展現一個例子(我使用2個Fragment做爲Activity的佈局,一個Fragment用於標題佈局,一個Fragment用於內容佈局):微信

fragment_title.xmlapp

<?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>

TitltFragment.classide

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;  
    }  
}

fragment_content.xml佈局

<?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>

ContentFragment.classthis

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);  
    }  
  
}

activity_main.xml3d

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

MainActivity.classcode

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);  
    }  
  
}

效果圖xml

四、動態的使用Fragment
上面已經演示了,最簡單的使用Fragment的方式~下面介紹如何動態的添加、更新、以及刪除Fragment
爲了動態使用Fragment,咱們修改一下Actvity的佈局文件,中間使用一個FrameLayout,下面添加四個按鈕~嘿嘿blog

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

底部四個按鈕的佈局就不貼了,到時看效果圖就明白了~~
下面主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);  
  
        // 設置默認的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();  
        // 開啓Fragment事務  
        FragmentTransaction transaction = fm.beginTransaction();  
  
        switch (v.getId())  
        {  
        case R.id.tab_bottom_weixin:  
            if (mWeixin == null)  
            {  
                mWeixin = new ContentFragment();  
            }  
            // 使用當前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();  
        // 事務提交  
        transaction.commit();  
    }  
  
}

能夠看到咱們使用FragmentManager對Fragment進行了動態的加載,這裏使用的是replace方法

代碼中間還有兩個Fragment的子類,ContentFragment上面已經見過,FriendFragment其實相似 fragment_friment.xml 與 fragment_content.xml也相似

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);  
    }  
  
}

效果圖

相關文章
相關標籤/搜索