Fragment 表示 Activity 中的行為或用戶界面部分鸭轮。您可以將多個(gè)Fragment組合在一個(gè) Activity 中來(lái)構(gòu)建多窗格 UI侈玄,以及在多個(gè) Activity 中重復(fù)使用某個(gè)Fragment。
Fragment必須始終嵌入在 Activity 中,其生命周期直接受宿主 Activity 生命周期的影響。
向 Activity 添加Fragment
通常玲昧,F(xiàn)ragment向宿主 Activity 貢獻(xiàn)一部分 UI,作為 Activity 總體視圖層次結(jié)構(gòu)的一部分嵌入到 Activity 中篮绿》跹樱可以通過(guò)兩種方式向 Activity 布局添加Fragment:
- 在 Activity 的布局文件內(nèi)聲明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.TestFragment"
android:id="@+id/list"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
android:name 屬性指定要在布局中實(shí)例化的 Fragment 類。
- 通過(guò)編程方式將片段添加到某個(gè)現(xiàn)有 ViewGroup
想在Activity 中執(zhí)行Fragment事務(wù)(如添加亲配、刪除或替換Fragment)尘应,必須使用 FragmentTransaction 『鸹ⅲ可以像下面這樣從 Activity 獲取一個(gè) FragmentTransaction 實(shí)例:
FragmentManager fragmentManager = getFragmentManager() //getSupportFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
可以使用 add() 方法添加一個(gè)Fragment犬钢,指定要添加的Fragment以及將其插入哪個(gè)視圖。
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
傳遞到 add() 的第一個(gè)參數(shù)是 ViewGroup鲸睛,即應(yīng)該放置Fragment的位置娜饵,由資源 ID 指定坡贺,第二個(gè)參數(shù)是要添加的Fragment官辈。一旦通過(guò) FragmentTransaction 做出了更改,就必須調(diào)用 commit() 以使更改生效遍坟。
在調(diào)用 commit() 之前拳亿,可以調(diào)用 addToBackStack()方法將事務(wù)添加到Fragment事務(wù)返回棧。 該返回棧由 Activity 管理愿伴,允許用戶通過(guò)按“返回” 按鈕返回上一Fragment狀態(tài)肺魁。
Fragment newFragment = new ExampleFragment();
//
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
//
transaction.commit();
上例中,newFragment 會(huì)替換目前在 R.id.fragment_container ID 所標(biāo)識(shí)的布局容器中的任何片段(如有)隔节。通過(guò)調(diào)用 addToBackStack() 可將替換事務(wù)保存到返回棧鹅经,以便用戶能夠通過(guò)按“返回” 按鈕撤消事務(wù)并回退到上一片段。
Fragment與Activity間通信
Fragment可以通過(guò) getActivity() 訪問(wèn) Activity 實(shí)例怎诫,并輕松地執(zhí)行在 Activity 布局中查找視圖等任務(wù)瘾晃。
View listView = getActivity().findViewById(R.id.list);
Activity 也可以使用 findFragmentById() 或 findFragmentByTag(),通過(guò)從 FragmentManager 獲取對(duì) Fragment 的引用來(lái)調(diào)用片段中的方法幻妓。
ExampleFragment fragment = (ExampleFragment) getFragmentManager().
findFragmentById(R.id.example_fragment);
Fragment聲明周期
Fragment必須是依存于Activity而存在的蹦误,因此Activity的生命周期會(huì)直接影響到Fragment的生命周期。
Activity 生命周期與片段生命周期之間的最顯著差異在于它們?cè)谄涓髯苑祷貤V械拇鎯?chǔ)方式。 默認(rèn)情況下强胰,Activity 停止時(shí)會(huì)被放入由系統(tǒng)管理的 Activity 返回棧(以便用戶通過(guò)“返回” 按鈕回退到Activity)舱沧。不過(guò),僅當(dāng)您在刪除片段的事務(wù)執(zhí)行期間通過(guò)調(diào)用 addToBackStack() 顯式請(qǐng)求保存實(shí)例時(shí)偶洋,系統(tǒng)才會(huì)將片段放入由宿主 Activity 管理的返回棧熟吏。
創(chuàng)建Fragment
要想創(chuàng)建片段,必須創(chuàng)建 Fragment 的子類或者它的子類(如DialogFragment玄窝,ListFragment分俯,PreferenceFragment)的子類。
通常哆料,至少應(yīng)實(shí)現(xiàn)以下生命周期方法:
- onCreate():應(yīng)該在方法內(nèi)內(nèi)初始化想在fragment暫透准簦或停止后恢復(fù)時(shí)保留的必需片段組件。
- onCreateView():系統(tǒng)會(huì)在Fragment 首次繪制其用戶界面時(shí)調(diào)用此方法东亦。 要想為Fragment 繪制 UI杏节,從此方法中返回的 View 必須是Fragment 布局的根視圖。如果Fragment 未提供 UI典阵,可以返回 null奋渔。
- onPause():通常應(yīng)該在此方法內(nèi)確認(rèn)在當(dāng)前用戶會(huì)話結(jié)束后仍然有效的任何更改(因?yàn)橛脩艨赡懿粫?huì)返回)。
下面是創(chuàng)建的一個(gè)Fragment
public class SecondFragment extends Fragment {
private static final String TEXT = "text";
private String mStr;
public SecondFragment() {
}
//在其他地方想要初始化fragment不推薦直接用new Fragment()
//推薦使用一下方式獲得fragment
public static SecondFragment newInstance(String text) {
SecondFragment fragment = new SecondFragment();
Bundle args = new Bundle();
args.putString(TEXT, text);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
Log.i(TAG, "onCreate()");
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mStr = getArguments().getString(TEXT);
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
savedInstanceState) {
Log.i(TAG, "onCreateView()");
View v = inflater.inflate(R.layout.fragment_second, container, false);
TextView textView = (TextView)v.findViewById(R.id.second_text);
textView.setText(mStr);
return v;
}
}
fragment的布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/second_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textSize="25sp"/>
</RelativeLayout>