簡述Fragment
什么是Fragment
fragment 在英語中是碎片的意思感猛,他是基于activity的一種控件达箍。一個fragment對應(yīng)著它自己的.xml布局文件來描述它的布局和.java文件來繼承Fragment這個類没龙。因為fragment基于activity且可以動態(tài)加載的緣故,它常被用來設(shè)計一些需要在一個activity內(nèi)實現(xiàn)頁面內(nèi)切的app,比如
或者一些為大屏幕設(shè)備如平板等打造的app,比如QQ HD
在這些布局中缎玫,用一個Activity承載了很多個動態(tài)的Fragment硬纤,可增可減,這樣做碘梢,即減少了activity的負擔(dān)咬摇,又更加能夠體現(xiàn)MVC設(shè)計框架中View層的靈活性,讓程序的界面設(shè)計更加模塊化煞躬,易于開發(fā)和維護肛鹏。
Frgment的生命周期(Lifecycle)
Android官方API文檔中很詳細的講解了Fragment的生命周期,點擊標題鏈接便可以訪問恩沛。在此簡述如下:
可以看到Fragment比Activity多了幾個額外的生命周期回調(diào)函數(shù):
onAttach(Activity);//當Activity與Fragment發(fā)生關(guān)聯(lián)時調(diào)用
onCreateView(LayoutInflater,ViewGroup,Bundle);//創(chuàng)建該Fragment的視圖
onActivityCreate(bundle);//當Activity的onCreate()在扰;方法返回時調(diào)用
onDestoryView();//與onCreateView相對應(yīng),當改Fragment被移除時調(diào)用
onDetach();//與onAttach()相對應(yīng)雷客,當Fragment與Activity的關(guān)聯(lián)被取消時調(diào)用
注意:除了onCreateView芒珠,其他的所有方法如果你重寫了,必須調(diào)用父類對于該方法的實現(xiàn)搅裙。
創(chuàng)建Fragment
- 1 靜態(tài)的使用Fragment
首先我先創(chuàng)建了一個空的Activity
MainActivity
接著我又創(chuàng)建了兩個Fragment的.xml文件皱卓,分別是fragment1.xml裹芝,和fragment2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:fitsSystemWindows="true"
tools:context=".MainActivity"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar android:id="@+id/toolbar"
android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<fragment
android:name="com.example.fuerm.myapplication.Fragment1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="50"
tools:layout="@layout/fragment1" />
<fragment
android:name="com.example.fuerm.myapplication.Fragment2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="50"
tools:layout="@layout/fragment2" />
</LinearLayout>
在Activity的布局代碼中,我們將兩個fragment直接像當作普通部件一樣娜汁,放入Activity的Layout中嫂易,在此我在MainActivity中采用了垂直線性布局,LayoutWight各占50%掐禁,代碼如上怜械,MainActivity的布局效果如下圖
以上就是Fragment靜態(tài)的使用方法。
- 2 Fragment的動態(tài)使用方法
接下來傅事,我們創(chuàng)建另一個工程缕允,帶有側(cè)邊漢堡菜單的APP.如圖
image.png
我們想實現(xiàn)當側(cè)邊漢堡菜單彈出時,點擊漢堡菜單的按鈕蹭越,主Activity的內(nèi)容也相應(yīng)改變障本。
首先還是想剛才一樣創(chuàng)建兩個Fragment.
然后再分別創(chuàng)建兩個繼承自Fragment的類 Fragment1 和Fragment2.
代碼如下:
public class Fragment1 extends Fragment{
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment1,container,false);
return v;
}
}
public class Fragment2 extends Fragment{
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment2,container,false);
return v;
}
}
然后我們需要在layout_content中添加一個布局,以作Fragment的Container.這個布局可以是LinearLayout响鹃,RelativeLayourt彼绷,F(xiàn)rameLayout或者其他,在此以FrameLayout為例茴迁,代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
android:id="@+id/fragment_container"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="@layout/app_bar_main"
tools:context=".MainActivity"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent" />
然后我們整個屏幕都用來顯示Fragment寄悯,所以其余的東西什么都不加。
然后堕义,我們需要在MainActivity.java中去創(chuàng)建 這兩個Fragment并動態(tài)的加載它們猜旬。
Fragment1 fragment1; //創(chuàng)建一個Fragment1對象
Fragment2 fragment2; //創(chuàng)建一個Fragment2對象
FragmentTranscation f; //創(chuàng)建一個FragmentTranscation對象,這個是用來動態(tài)加載Fragment的
之后在MainActivity.java中的 onNavigationItemSelected(MenuItem item) 方法中,我們加入如fragment動態(tài)切換的方法:
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
f = getFragmentManager().beginTransaction(); //給f初始化
fragment1 = new Fragment1(); //對象初始化
fragment2 = new Fragment2(); //對象初始化
//建議用switch語句倦卖,這是系統(tǒng)自己生成的
if (id == R.id.nav_camara) {
//以下是重點
f = getFragmentManager().beginTransaction();//調(diào)用FragmentManager洒擦,并開始事務(wù)處理
f.replace(R.id.fragment_container, fragment1);//替換一個fragment給我們的FrameLayout,這里需要說明一下怕膛,正常邏輯你應(yīng)該在你的OnCreat( )方法中去實現(xiàn)FramLayout的初始布局熟嫩。方法和如下是一樣的
f.commit();//提交事務(wù)
} else if (id == R.id.nav_gallery) {
f.replace(R.id.fragment_container, fragment2);//替換
f.commit();
//因為我們就兩個fragment,而菜單數(shù)多余我們褐捻,僅僅為了展示掸茅,下面的就不管了
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
總結(jié)一下
動態(tài)的使用需要調(diào)用FragmentTranscation的FragmentMannger,通過getFragmentManager( )獲得柠逞,然后以提交事務(wù)的方式commit( )來添加add( )/replace( )或替換當前布局中的頁面昧狮。
現(xiàn)在程序可以跑起來了,效果如下