Android Fragment使用


         
       通常地 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(). 
 
/**
* @author 张兴业
* 邮箱:xy-zhang#163.com
* android开发进阶群:278401545
*
*/
原文地址:https://www.cnblogs.com/bhlsheji/p/4325550.html