概念
Fragment英文原意是碎片暇韧,片段的意思,為了應(yīng)對(duì)android的碎片化含衔,F(xiàn)ragmnet的概念在Android3.0中被引入進(jìn)來煎娇,主要目的是用在大屏幕設(shè)備上--例如平板電腦上二庵,支持更加動(dòng)態(tài)和靈活的UI設(shè)計(jì)贪染。平板電腦的屏幕比手機(jī)大得多,有更多的空間來放更多的UI組件催享,并且這些組件之間會(huì)產(chǎn)生更多的交互杭隙。
Fragment在應(yīng)用中應(yīng)當(dāng)是一個(gè)模塊化和可重用的組件,因?yàn)镕ragment定義了自己的布局因妙,以及通過使用它自己的生命周期回調(diào)方法定義了它自己的行為痰憎,你可以將Fragment包含到多個(gè)Activity中,一個(gè)Activiy也可以包含多個(gè)Fragment攀涵。
下面這張圖可以幫助理解Fragment的概念:
知識(shí)概要
- Fragment可以作為Activity界面的一部分組成出現(xiàn)
- 可以在一個(gè)Activity中同時(shí)出現(xiàn)多個(gè)Fragment铣耘,并且一個(gè)Fragment也可以在多個(gè)Activity中使用
- 在Activity運(yùn)行過程中,可以添加以故,移除或替換Fragment
- Fragment可以響應(yīng)自己的輸入時(shí)間蜗细,并且有自己的生命周期,其生命周期受宿主Activity的生命周期影響
Fragment的使用
創(chuàng)建Fragment
靜態(tài)創(chuàng)建
靜態(tài)創(chuàng)建需要在在布局文件中聲明Fragment怒详,需要特別注意的是Fragment中的android:name屬性指定了在layout中實(shí)例化的Fragment類 ,同時(shí)必須要標(biāo)識(shí)Fragment炉媒。
標(biāo)識(shí)Fragment的方法:
android:id 屬性提供一個(gè)唯一的ID
android:tag 屬性提供一個(gè)唯一的字符串
** 創(chuàng)建方法:**
- 在布局文件中聲明一個(gè)fragment組件,name指向3中創(chuàng)建的類對(duì)象
<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.w2.test.MainActivity"
android:orientation="vertical">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="button1"
android:text="Button1"
android:textSize="18sp"
/>
<!--聲明一個(gè)fragment-->
<fragment
android:id="@+id/fragment"
android:name="com.w2.test.MyFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
2.創(chuàng)建fragment布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="這是一個(gè)靜態(tài)加載的Fragment"
android:id="@+id/textView"
android:layout_gravity="center_horizontal"
android:textSize="20sp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change"
android:id="@+id/button"
android:layout_gravity="center_horizontal" />
</LinearLayout>
3.創(chuàng)建MyFragment類繼承Fragment對(duì)象昆烁,重寫onCreateView方法返回布局文件的View
public class MyFragment extends Fragment{
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
* resource:Fragment需要加載的布局文件
* root:加載layout的父ViewGroup
* attactToRoot:false吊骤,不返回父ViewGroup
*/
View v = inflater.inflate(R.layout.fragment,container,false);
View view = inflater.inflate(R.layout.fragment, container, false);
final TextView text=(TextView) v.findViewById(R.id.textView);
Button button=(Button) v.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
text.setText("測(cè)試成功");
}
});
return v;
}
}
動(dòng)態(tài)創(chuàng)建
在Java代碼中撰寫代碼將Fragment添加到Activity layout中。
add():添加一個(gè)Fragment静尼,指定要添加的Fragment和插入的View
與此類似的還有remove(),repalce()等
諸如上述對(duì)Fragment進(jìn)行添加白粉,移除,替換以及執(zhí)行其他動(dòng)作鼠渺,提交給Activity的每一套變化被稱為一個(gè)事物蜗元,處理這類事物需要Fragment Manager,通過FragmentManager開啟事務(wù)系冗。
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction beginTransaction = fragmentManager.beginTransaction();
每一個(gè)事務(wù)都是同時(shí)執(zhí)行一套變化奕扣,可以在一個(gè)事務(wù)中設(shè)置所要執(zhí)行的操作,然后提交給Activity掌敬,之后必須要調(diào)用commit方法惯豆。
如果允許用戶通過按下BACK按鍵返回到前一個(gè)Fragment狀態(tài),調(diào)用commit之前可以加入addToBackStack()方法奔害。
FragmentManager fragmentManager = getFragmentManager(); //獲取FragmentManager
FragmentTransaction beginTransaction = fragmentManager.beginTransaction(); //開啟事務(wù)
beginTransaction.add(R.id.frame, fragment2); //添加Fragment楷兽,參數(shù)1containerViewId傳入Fragment的父布局,參數(shù)2fragment穿入Fragment的實(shí)例化對(duì)象
beginTransaction.addToBackStack(null); //增加回退功能华临,回到上一個(gè)事務(wù)狀態(tài)
beginTransaction.commit(); //提交事務(wù)
Fragment的生命周期
-
Fragment生命周期圖
-
與Activity生命周期對(duì)比
每個(gè)方法的回調(diào)條件:
onCreateView()
每次創(chuàng)建都會(huì)繪制Fragment的View組件時(shí)回調(diào)該方法
Fragment第一次繪制它的用戶界面的時(shí)候芯杀,系統(tǒng)會(huì)調(diào)用此方法,為了繪制Fragment的UI,此方法必須返回一個(gè)View揭厚,如果不顯示UI却特,返回null即可。onAttach
當(dāng)Fragment被添加到Activity時(shí)候會(huì)回調(diào)這個(gè)方法筛圆,并且只調(diào)用一次onCreate
創(chuàng)建Fragment時(shí)會(huì)回調(diào)裂明,只會(huì)調(diào)用一次onActivityCreated
當(dāng)Fragment所在的Activty啟動(dòng)完成后調(diào)用onStart
啟動(dòng)FragmentonResume
恢復(fù)Fragment時(shí)會(huì)被回調(diào),調(diào)用onStart()方法后面一定會(huì)調(diào)用onResume()方法onPause
暫停FragmentonStop
停止FragmentonDestroyView
銷毀Fragment所包含的View組件時(shí)onDestroy
銷毀Fragment時(shí)會(huì)被回調(diào)onDetach
Fragment從Activity中刪除時(shí)會(huì)回調(diào)該方法太援,并且這個(gè)方法只會(huì)調(diào)用一次
Fragment與Activity互相通信
Activity向Fragment傳遞數(shù)據(jù)
在Activity中創(chuàng)建Bundle數(shù)據(jù)包闽晦,并調(diào)用Fragment的setArgument(Bundle bundle)方法。這種方式是在加載Fragment之前傳遞數(shù)據(jù)的提岔。
Activity:
//動(dòng)態(tài)加載Fragment的同時(shí)傳遞數(shù)據(jù)
String text = editText.getText().toString(); //獲取要傳遞的數(shù)據(jù)
Bundle bundle = new Bundle();
if (text!=null){
bundle.putString("msg",text);
}
MyFragment fragment = new MyFragment();
fragment.setArguments(bundle);
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.frame,fragment,"MyFragment");
transaction.addToBackStack(null);
transaction.commit();
Fragment:
//獲取數(shù)據(jù)并令TextView顯示
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment,container,false);
TextView text=(TextView) v.findViewById(R.id.textView);
text.setText(getArguments().get("msg").toString());
return v;
}
** 注意仙蛉,這里取得傳遞過來的數(shù)據(jù)用的是@getArgument方法,@setArgument中傳入的bundle只是一個(gè)數(shù)據(jù)類型碱蒙,與savedInstanceState這個(gè)參數(shù)沒有關(guān)系捅儒。我之前用savedInstanceState.getString()獲取數(shù)據(jù)一直錯(cuò)誤,很久都找不到錯(cuò)誤振亮。**
Fragment向Activity傳遞數(shù)據(jù)
需要在Fragment中定義回調(diào)接口巧还,再讓包含該Fragment的Activity實(shí)現(xiàn)該回調(diào)接口。這樣Fragment可以調(diào)用該回調(diào)方法傳數(shù)據(jù)給Activity坊秸。
- 在Fragment中定義接口麸祷,并在接口中定義傳遞數(shù)據(jù)的抽象方法
public interface MyListener{
public void send(String code);
}
- 令A(yù)ctivity實(shí)現(xiàn)定義的接口,并重寫定義的方法
public class MainActivity extends AppCompatActivity implements MyFragment.MyListener
...
@Override
public void send(String code) {
}
- 在Fragment中將創(chuàng)建接口對(duì)象并指向Activity褒搔,最后傳入String
MyListener listener;
@Override
public void onAttach(Activity activity) { //不一定非要在onAttach中
listener = (MyListener) activity;
super.onAttach(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment,container,false);
TextView text=(TextView) v.findViewById(R.id.textView);
text.setText(getArguments().get("msg").toString());
listener.send("這是發(fā)送給Activity的數(shù)據(jù)");//也不一定非在onCreateView中
return v;
}
- 在Activity中接收數(shù)據(jù)
@Override
public void send(String code) {
editText.setText(code);
}
Activity向靜態(tài)加載Fragment傳遞數(shù)據(jù)
首先按靜態(tài)加載方式創(chuàng)建Fragment
在Fragment的創(chuàng)建數(shù)據(jù)用來接收傳來的數(shù)據(jù)阶牍,設(shè)置get和set方法
public String a;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
- 在Activity通過Fragment.findFragmentById找到Fragment,通過set方法傳遞數(shù)據(jù)
FragmentManager fragmentManager = getFragmentManager();
MyFragment fragment = (MyFragment) fragmentManager.findFragmentById(R.id.fragment);
fragment.setA(text);
- 最后在Fragment中通過get方法接收數(shù)據(jù)