1. 程式人生 > >Android基礎知識元件篇-----------Fragment

Android基礎知識元件篇-----------Fragment

   Fagment :為了讓程式更加合理和充分的利用大螢幕的空間,而嵌入在活動當中的UI片段

一、Fragment的基本用法

新建Java類繼承自Fragment,重寫onCreateView()方法載入fragment的佈局,程式碼如下:

public class MyFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_xxx,container,false);
        return  view;
        
    }
}

在Activity的佈局中引用的時候在xml檔案中加fragment標籤即可,

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <fragment
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:id="@+id/left_fragment"
            android:name="com.example.administrator.mycontext.MyFragment"
            android:layout_weight="1"/>
    <fragment
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:id="@+id/right_fragment"
            android:name="com.example.administrator.mycontext.MyFragment"
            android:layout_weight="1"/>

</LinearLayout>

二、Fragment的動態新增

(1)建立待新增的碎片例項,(2)獲取FragmentManager,在活動中可以直接通過呼叫getSupportFragmentManager()方法得到(3)開啟一個事務,(4)替換呼叫replace()方法,(5)提交事務

private void  replaceFragment(Fragment fragment){
    FragmentManager fragmentManager=getSupportFragmentManager();
    FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.layout,fragment);
    fragmentTransaction.addToBackStack(null)//模擬返回棧
    fragmentTransaction.commit();
}

同時也需要將活動的佈局檔案中的待替換的<fragment>標籤換成<FrameLayout>

三、Fragment和活動之間通訊

在活動中得到Fragment的例項 

OneFragment onfragment=(OneFragment)getSupportFragmentManager().findFragmentById(R.id.xxx);

在Fragment中得到活動的例項

MainActivity activity=(MainActivity)getActivity();

四、Fragment的生命週期

執行態:表示碎片是可見的

暫停態:活動進入暫停時,跟它關聯的碎片也進入暫停態

停止態:活動進入停止態時,跟它相關聯的碎片也進入停止態

銷燬態:活動被銷燬時,跟它相關聯的碎片也進入銷燬態

                                                                        生命週期示意圖