Fragment的簡單用法

創建碎片

先新建一個碎片的佈局example_fragment.xml,然後再創建自己的fragment 類ExampleFragment 繼承自Fragment,並重寫其中的onCreateView() 方法:

public static class ExampleFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.example_fragment, container, false);
    }
}

inflate() 方法將xml資源轉化爲view 對象並返回。它接收三個參數:

  • 需要加載的佈局文件的ID;
  • 一個ViewGroup 作爲加載佈局的父對象。這裏傳入onCreateView() 的參數container 就可以;
  • 第三個參數是一個布爾值,如果傳入true的話,將會連同父對象一起被返回。


將碎片添加到Activity

添加碎片的方法有靜態添加和動態添加兩種

1. 靜態添加

這種方法直接在Activity 的佈局文件中聲明Fragment,例如:

<?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>

name 屬性指定碎片佈局所對應的類。

2. 動態添加

在Activity 中添加、替換、刪除等一系列操作稱作一項“事務”。要開啓一項事務,需要一個FragmentTransaction 對象。獲得FragmentTransaction 對象的方法如下:

FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

然後就可以調用add() 方法添加碎片了:

ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();

可以同時進行多項操作,在操作完畢以後用commit() 方法提交。


爲碎片添加返回棧

如果想要點擊返回鍵的時候返回到上一個狀態,需要爲事務添加返回棧,在commit() 之前調用addToBackStack() 方法即可:

			transaction.addToBackStack(null);

碎片與活動的通信

碎片與活動的通信,說白了也就是相互調用對方的方法。其實也就是只需要獲取對方對象的實例就可以了。

碎片可以通過getActivity() 方法獲取Activity 的實例,例如獲取Activity 的Layout 中的View 對象:

View listView = getActivity().findViewById(R.id.list);

同樣的,在Activity 中你也可以藉助FragmentManager 對象的findFragmentById() 或者findFragmentByTag() 方法來獲取Fragment 實例:

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);

後面還會詳細說到。

發佈了51 篇原創文章 · 獲贊 3 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章