Android UI詳解之Fragment加載

jopen 11年前發布 | 43K 次閱讀 Android Android開發 移動開發

fragment做為宿主activity UI的一部分, 被作為activity整個view hierarchy的一部分被嵌入. 有2種方法你可以添加一個fragment到activity layout:

一、在activity的layout文件中聲明fragment

 

你可以像為View一樣, 為fragment指定layout屬性(sdk3.0以后).
例子是一個有2個fragment的activity:

<?xml version="1.0" encoding="utf-8"?>
<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.news.ArticleListFragment"
            android:id="@+id/list"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
     <fragment android:name="com.example.news.ArticleReaderFragment"
            android:id="@+id/viewer"
            android:layout_weight="2"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
  </LinearLayout>

<fragment> 中的 android:name 屬性指定了在layout中實例化的Fragment類.

當系統創建這個activity layout時, 它實例化每一個在layout中指定的fragment,并調用每一個上的onCreateView()方法,來獲取每一個fragment的layout. 系統將從fragment返回的 View 直接插入到<fragment>元素所在的地方.

注意: 每一個fragment都需要一個唯一的標識, 如果activity重啟,系統可以用來恢復fragment(并且你也可以用來捕獲fragment來處理事務,例如移除它.)

有3種方法來為一個fragment提供一個標識:
為 android:id 屬性提供一個唯一ID.
為 android:tag 屬性提供一個唯一字符串.
如果以上2個你都沒有提供, 系統使用容器view的ID.

二、使用FragmentManager將fragment添加到一個已存在的ViewGroup.

當activity運行的任何時候, 都可以將fragment添加到activity layout.只需簡單的指定一個需要放置fragment的ViewGroup.為了在你的activity中操作fragment事務(例如添加,移除,或代替一個fragment),必須使用來自 FragmentTransaction 的API.

可以按如下方法,從你的Activity取得一個 FragmentTransaction 的實例:

FragmentManager fragmentManager = getFragmentManager(); 
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

然后你可以使用 add() 方法添加一個fragment, 指定要添加的fragment, 和要插入的view.

ExampleFragment fragment = new ExampleFragment();
 fragmentTransaction.add(R.id.fragment_container, fragment); 
fragmentTransaction.commit();

add()的第一個參數是fragment要放入的ViewGroup, 由resource ID指定, 第二個參數是需要添加的fragment.一旦用FragmentTransaction做了改變,為了使改變生效,必須調用commit().

來自:http://blog.csdn.net/x359981514/article/details/8707976

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!