Fragment 有自己的生命周期和回調(diào)方法。

image
創(chuàng)建 Fragment 通過擴展 Fragment 類實現(xiàn),也可以擴展其之類 DialogFragment、ListFragment、PreferenceFragment。
要想為片段提供布局,您必須實現(xiàn) onCreateView() 回調(diào)方法
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);
}
}
向 Activity 添加片段
在 Activity 的布局文件內(nèi)聲明片段
<?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>
android:name 屬性指定要在布局中實例化的 Fragment 類。
通過編程方式將片段添加到某個現(xiàn)有 ViewGroup
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
管理片段
通過 FragmentManager fragmentManager = getFragmentManager(); 管理片段。
執(zhí)行片段事務(wù)
以下示例說明了如何將一個片段替換成另一個片段,以及如何在返回棧中保留先前狀態(tài):
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
與 Activity 通信
片段可以通過 getActivity() 訪問 Activity 實例
View listView = getActivity().findViewById(R.id.list);
Activity 也可以使用 findFragmentById() 或 findFragmentByTag(),通過從 FragmentManager 獲取對 Fragment 的引用來調(diào)用片段中的方法
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
片段的生命周期

image