Android应用开发中使用Fragment的入门学习教程

2019-12-10 18:59:17刘景俊

      你可以像为View一样, 为fragment指定layout属性(sdk3.0以后).
      例子是一个有2个fragment的activity:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://www.easck.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.