Fragment(碎片)動態建立

Fragment(碎片)動態的建立java

       動態建立不用像 靜態同樣要在主activity_main.xml佈局文件
佈局fragment(碎片)。
       動態建立碎片只須要在activity_main.xml佈局文件裏放須要的
小布局(其實至關於fragment(碎片))
示例代碼
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
 
    <LinearLayout
        android:id="@+id/text_layout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="6"
        android:background="#ebebeb" />
  
</LinearLayout>android

上面的activity_main.xml佈局文件裏只放了一個小的 線性佈局
但和靜態建立的時候 仍是有點類似的 -- 只不過靜態建立 activity_main.xml
佈局文件裏放的是fragment(碎片)。 -- 基礎階段先這樣理解。小程序


=================================================================佈局

 

Fragment動態的建立xml

     一、首先要繼承Fragment類
  二、獲取Fragment管理器
        -- FragmentManager fragmentManager = getSupportFragmentMannager();
  三、用Fragment管理器啓動一個事物
        -- FragmentTransaction transaction = fragmentManager.beginTransaction();
     四、而後就能夠利用事物 -- transaction 自帶的添加 刪除 替換 操做數據了
  五、操做完數據後 -- 注意:要提交事物
        -- transaction.commit();
    
--------------------繼承

事物自帶添加 刪除 替換 方法說明rem

添加
//第一個參數 -- 在主activity_main.xml佈局文件裏放的線性小布局
//該小布局能夠放其餘的控件視圖 -- 這樣就至關於一個碎片了(動態建立)get

//第二個參數 -- Left.java類,該類繼承Fragment -- 碎片類
//該類中重寫的onCreateView 會返回View(視圖) 到第一個參數 -- 小布局上(碎片)it

//第三個參數 -- 標誌 -- 當要修改或者刪除的時候 能夠利用
    transaction.add(R.id.text_layout,left_fragment,"My_left_fragment");
 
刪除
//先找到須要刪除的標誌
     Fragment tag = transaction.findFragmentByTag("My_left_fragment");
  //而後刪除相應的標誌
  transaction.remove(tag);
  //不要忘記提交事物
  transaction.commit();
 
替換io

//找到要替換的標誌
     Fragment tag = transaction.findFragmentByTag("My_left_fragment");

if(tag == right_fragment){//判斷要替換的標誌是否是Right_fragment碎片類的

//若是是 就找到該類 在找到該標誌 把要替換的內容替換掉
//經過第二個參數 返回來的新視圖來替換原來的視圖就行

//第三個參數 -- 替換後的新標誌

    transaction.replace(R.id.text_layout,left_fragment,"My_left_fragment");

}

 
==================================================================

動態建立就先了解這些 後面經過一個小程序理解Fragment(碎片)的動態建立

相關文章
相關標籤/搜索