android基礎之fragment學習

fragment是嵌在activity內部的模塊,其有本身的生命週期,但其生命週期必須依賴於activity的存在而存在,在API 11以前每一個fragment必須與父FragmentActivity相關聯,API 11以後就能夠經過activity實現這種關聯。在activity中嵌入fragment有兩種方式,一種是經過在xml文件中以下聲明, java

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <fragment android:name="com.example.android.fragments.HeadlinesFragment"
              android:id="@+id/headlines_fragment"
              android:layout_weight="1"
              android:layout_width="0dp"
              android:layout_height="match_parent" />


    <fragment android:name="com.example.android.fragments.ArticleFragment"
              android:id="@+id/article_fragment"
              android:layout_weight="2"
              android:layout_width="0dp"
              android:layout_height="match_parent" />


</LinearLayout> android

[java]  view plain copy
  1. <p>此種定義的fragmnet不能夠在activity運行時remove掉,通常用於大屏幕的佈局。</p><p>另外一種能夠定義一個存儲fragment的容器,好比</p>  
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
此種定義的fragment能夠實如今activity中實現add和remove等操做,但需注意的是此種必須在activity的oncreate方法中初始化fragment.以下
   ArticleFragment newFragment = new ArticleFragment();

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();


            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack so the user can navigate back
            transaction.replace(R.id.fragment_container, newFragment);
            transaction.addToBackStack(null);


            // Commit the transaction
            transaction.commit(); 佈局

對於fragment的操做,是經過FragmnetTransaction實現的。首先經過getSupportedFragmentManager獲得FragmentManager using Support Library APIs,而後調用beginTransaction獲得FragmentTransaction.
注意,你能夠執行多種fragment的操做用同一個fragmentTransaction,當執行完全部的操做後fragmentTransaction執行commit操做來保存對於fragment執行的各類操做。
當對fragment執行完removve操做後若是須要回到以前的fragment,須要在執行完remove操做後執行addToBackStack(String name);該方法中的string參數來給每一個transaction一個惟一的標示,若是不想爲其起名字能夠addToBackStack(null).
fragment間的數據傳遞能夠經過Bundle實現。語法以下fragment.setArgments(bundle);獲得傳遞的bundle,Bundle bundle=getArgments();

示例代碼連接:http://download.csdn.net/detail/u010095768/5493793 this

相關文章
相關標籤/搜索