Fragment的簡單使用

Fragment,可以理解爲是代替activity的輕量級的替代品,而且使用非常靈活多變,而且管理方便,對整個的程序的可維護性和可擴展性都起到很好的的幫助,可以讓主函數看起來更加清晰明瞭。

學習後總結了一下,發現在實際開發中Fragment最常用的地方是:Viewpager+Fragment;側滑Fragment


Fragment有自己的生命週期:(其生命週期會受到ativity的生命週期的控制)


onAttach(Activity):當Fragment與Activity發生關聯時調用。


onCreateView(LayoutInflater, ViewGroup,Bundle):創建該Fragment的視圖


onActivityCreated(Bundle):當Activity的onCreate方法返回時調用


onDestoryView():與onCreateView想對應,當該Fragment的視圖被移除時調用


onDetach():與onAttach相對應,當Fragment與Activity關聯被取消時調用


注意:除了onCreateView,其他的所有方法如果你重寫了,必須調用父類對於該方法的實現,


獲取FragmentManage的方式:

getFragmentManager() // v4中,getSupportFragmentManager


主要的操作都是FragmentTransaction的方法

FragmentTransaction transaction = fm.benginTransatcion();//開啓一個事務


transaction.add() 

往Activity中添加一個Fragment

transaction.remove()

從Activity中移除一個Fragment,如果被移除的Fragment沒有添加到回退棧(回退棧後面會詳細說),這個Fragment實例將會被銷燬。

transaction.replace()

使用另一個Fragment替換當前的,實際上就是remove()然後add()的合體~

transaction.hide()

隱藏當前的Fragment,僅僅是設爲不可見,並不會銷燬

transaction.show()

顯示之前隱藏的Fragment

detach()

會將view從UI中移除,和remove()不同,此時fragment的狀態依然由FragmentManager維護。

attach()

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

transatcion.commit()//提交一個事務

注意:常用Fragment的哥們,可能會經常遇到這樣Activity狀態不一致:State loss這樣的錯誤。主要是因爲:commit方法一定要在Activity.onSaveInstance()之前調用。

上述,基本是操作Fragment的所有的方式了,在一個事務開啓到提交可以進行多個的添加、移除、替換等操作。

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


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

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

c、remove和detach有一點細微的區別,在不考慮回退棧的情況下,remove會銷燬整個Fragment實例,而detach則只是銷燬其視圖結構,實例並不會被銷燬。那麼二者怎麼取捨使用呢?如果你的當前Activity一直存在,那麼在不希望保留用戶操作的時候,你可以優先使用detach。



一:Fragment的靜態使用:

這是使用Fragment最簡單的一種方式,把Fragment當成普通的控件,直接寫在Activity的佈局文件中。步驟:

1、繼承Fragment,重寫onCreateView決定Fragemnt的佈局

2、在Activity中聲明此Fragment,就當和普通的View一樣


activity_main.xml

<strong><span style="font-size: 14px;"><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" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">


    <fragment
        android:id="@+id/id_fragment_title"
        </span><span style="font-size:24px;">android:name="ivo_chuanzhi.fragment.MyFragment"</span><span style="font-size: 14px;">
        android:layout_width="fill_parent"
        android:layout_height="45dp" />

    <fragment
        android:layout_below="@id/id_fragment_title"
        android:id="@+id/id_fragment_content"
        </span></strong><span style="font-size:24px;font-weight: bold;">android:name="ivo_chuanzhi.fragment.Two_fragment"</span><span style="font-weight: bold; font-size: 14px;">
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</RelativeLayout></span>

主函數什麼都不用寫


這裏給出一個MyFragment的代碼:

public class MyFragment extends Fragment {


    private  View view;
    private TextView textView;

    //Context context;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

       // context = getActivity();   可以通過上下文對象get到當前Activity

        //爲MyFragment增加視圖,該視圖是one_fragment
        view = inflater.inflate(R.layout.one_fragment,container,false);
        textView = (TextView) view.findViewById(R.id.textView);


       return view;
    }


}


二:Fragment的動態使用(使用原博主的代碼)

下面介紹如何動態的添加、更新、以及刪除Fragment

爲了動態使用Fragment,我們修改一下Actvity的佈局文件,中間使用一個FrameLayout,下面添加四個按鈕

<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

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方法
注:如果使用Android3.0以下的版本,需要引入v4的包,然後Activity繼承FragmentActivity,然後通過getSupportFragmentManager獲得FragmentManager。不過還是建議版Menifest文件的uses-sdk的minSdkVersion和targetSdkVersion都改爲11以上,這樣就不必引入v4包了

轉載自:http://blog.csdn.net/lmj623565791/article/details/37970961#comments

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章