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

相关文章
相关标签/搜索