我們日常開發中經常會使用到fragment,通常會放置在主頁面上,方便切換展示信息。它擁有自己的生命週期,可以接受處理用戶的事件,並且你可以在一個Activity中動態的添加,替換,移除不同的Fragment。
一、生命週期
第一張圖展示了fragment的生命週期,第二章圖展示了 Activity 與 Fragment 生命週期的對比
Fragment比Activity多了幾個生命週期的回調方法
-
onAttach(Activity) 當Fragment與Activity發生關聯的時候調用(在這個方法中可以獲得所在的activity)
-
onCreateView(LayoutInflater, ViewGroup, Bundle) 創建該Fragment的視圖
-
onActivityCreated(Bundle) 當Activity的onCreated方法返回時調用
-
onDestroyView() 與onCreateView方法相對應,當該Fragment的視圖被移除時調用
-
onDetach() 與onAttach方法相對應,當Fragment與Activity取消關聯時調用
一旦activity進入resumed狀態(也就是running狀態),你就可以自由地添加和刪除fragment了。因此,只有當activity在resumed狀態時,fragment的生命週期才能獨立的運轉,其它時候是依賴於activity的生命週期變化的。
二、使用
1.靜態使用
步驟:
- 創建一個類繼承Fragment,重寫onCreateView方法,來確定Fragment要顯示的佈局
- 在Activity中聲明該類,與普通的View對象一樣
代碼演示:
MyFragment對應的佈局文件item_fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@color/colorAccent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="@mipmap/ic_launcher" />
</RelativeLayout>
繼承Frgmanet的類MyFragment【請注意導包的時候導v4的Fragment的包】
public class MyFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//參數1:佈局文件的id 參數2:容器 參數3:是否將這個生成的View添加到這個容器中去
View v = inflater.inflate(R.layout.item_fragment, container, false);
return v;
}
}
Activity對應的佈局文件
<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:orientation="vertical"
tools:context="com.usher.fragment.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:gravity="center"
android:text="Good Boy" />
<fragment
android:id="@+id/myfragment"
android:name="com.usher.fragment.MyFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
2.動態使用
步驟:
- 編寫不同的fragment界面和類
- 在activity使用FragmentManager對fragment進行操作
代碼演示:
Fragment對應的佈局文件item_fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@color/colorAccent" //背景紅色
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="@mipmap/ic_launcher" />
</RelativeLayout>
繼承Frgmanet的類MyFragment
public class MyFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.item_fragment, container, false);
return v;
}
}
Fragment2對應的佈局文件item_fragment2.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@color/colorPrimary" //背景藍色
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="@mipmap/ic_launcher" />
</RelativeLayout>
繼承Fragment的類MyFragment2
public class MyFragment2 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.item_fragment2, container, false);
return v;
}
}
MainActivity對應的佈局文件
<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:orientation="vertical"
tools:context="com.usher.fragment.MainActivity">
<Button
android:id="@+id/bt_red"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Red" />
<Button
android:id="@+id/bt_blue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Blue" />
<FrameLayout
android:id="@+id/myframelayout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
MainActivity類
public class MainActivity extends AppCompatActivity {
private Button bt_red;
private Button bt_blue;
private FragmentManager manager;
private MyFragment fragment1;
private MyFragment2 fragment2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
fragment1 = new MyFragment();
fragment2 = new MyFragment2();
//初始化FragmentManager對象
manager = getSupportFragmentManager();
//使用FragmentManager對象用來開啓一個Fragment事務
FragmentTransaction transaction = manager.beginTransaction();
//默認顯示fragment1
transaction.add(R.id.myframelayout, fragment1).commit();
//對bt_red設置監聽
bt_red.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.myframelayout, fragment1).commit();
}
});
//對bt_blue設置監聽
bt_blue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.myframelayout, fragment2).commit();
}
});
}
private void initView() {
bt_red = (Button) findViewById(R.id.bt_red);
bt_blue = (Button) findViewById(R.id.bt_blue);
}
}
FragmentTransaction的方法主要有以下幾種:
-
transaction.add() 向Activity中添加一個Fragment
-
transaction.remove() 從Activity中移除一個Fragment,如果被移除的Fragment沒有添加到回退棧(回退棧後面會詳細說),這個Fragment實例將會被銷燬
-
transaction.replace() 使用另一個Fragment替換當前的,實際上就是remove()然後add()的合體
-
transaction.hide() 隱藏當前的Fragment,僅僅是設爲不可見,並不會銷燬
-
transaction.show() 顯示之前隱藏的Fragment
-
detach() 會將view從UI中移除,和remove()不同,此時fragment的狀態依然由FragmentManager維護
-
attach() 重建view視圖,附加到UI上並顯示
-
ransatcion.commit() 提交事務
三、回退棧
Fragment的回退棧是用來保存每一次Fragment事務發生的變化 如果你將Fragment任務添加到回退棧,當用戶點擊後退按鈕時,將看到上一次的保存的Fragment。一旦Fragment完全從後退棧中彈出,用戶再次點擊後退鍵,則退出當前Activity
-
首先顯示第一個FragmentOne頁面有一個Button in FragmentOne,上面有個輸入框顯示的是Fragment One
-
然後輸入change,點擊Button in FragmentOne,然後顯示第二個Fragment,裏面有一個Button in FragmentTwo,一個輸入框顯示Fragment Two
-
輸入change,點擊按鈕,顯示第三個Fragment,上面有個Button in FragmentThree,點擊按鈕顯示出一個Toast
-
【注意】點擊返回鍵,跳轉到前一個FragmentTwo,這個時候可以看到上面的輸入框中顯示的是Fragment Two change,也就是說保留了我們離開這個Fragment時候他所呈現的狀態
-
【注意】再點擊返回鍵,跳轉到FragmentOne,但是這個時候我們可以看到上面的輸入框中只有Fragment One,並沒有change這幾個字母
那麼原因是什麼?
這裏先要學習一個方法:FragmentTransaction.addToBackStack(String)【把當前事務的變化情況添加到回退棧】
代碼如下:
MainActivity的佈局文件
<RelativeLayout 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" >
<FrameLayout
android:id="@+id/id_content"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
</RelativeLayout>
MainActivity.java文件【這裏添加的是app包下的Fragment,推薦v4包下的】
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
FragmentManager fm = getFragmentManager();
FragmentTransaction tx = fm.beginTransaction();
tx.add(R.id.id_content, new FragmentOne(),"ONE");
tx.commit();
}
}
FragmentOne.java文件
public class FragmentOne extends Fragment implements OnClickListener {
private Button mBtn;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
mBtn = (Button) view.findViewById(R.id.id_fragment_one_btn);
mBtn.setOnClickListener(this);
return view;
}
@Override
public void onClick(View v) {
FragmentTwo fTwo = new FragmentTwo();
FragmentManager fm = getFragmentManager();
FragmentTransaction tx = fm.beginTransaction();
tx.replace(R.id.id_content, fTwo, "TWO");
tx.addToBackStack(null);
tx.commit();
}
}
Fragment的點擊事件裏寫的是replace方法,相當於remove和add的合體,並且如果不添加事務到回退棧,前一個Fragment實例會被銷燬。這裏很明顯,我們調用tx.addToBackStack(null)將當前的事務添加到了回退棧,所以FragmentOne實例不會被銷燬,但是視圖層次依然會被銷燬,即會調用onDestoryView和onCreateView。所以【請注意】,當之後我們從FragmentTwo返回到前一個頁面的時候,視圖層仍舊是重新按照代碼繪製,這裏僅僅是是實例沒有銷燬,因此顯示的頁面中沒有change幾個字。
FragmentTwo.java文件
public class FragmentTwo extends Fragment implements OnClickListener {
private Button mBtn ;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_two, container, false);
mBtn = (Button) view.findViewById(R.id.id_fragment_two_btn);
mBtn.setOnClickListener(this);
return view ;
}
@Override
public void onClick(View v) {
FragmentThree fThree = new FragmentThree();
FragmentManager fm = getFragmentManager();
FragmentTransaction tx = fm.beginTransaction();
tx.hide(this);
tx.add(R.id.id_content , fThree, "THREE");
tx.addToBackStack(null);
tx.commit();
}
}
這裏點擊時,我們沒有使用replace,而是先隱藏了當前的Fragment,然後添加了FragmentThree的實例,最後將事務添加到回退棧。這樣做的目的是爲了給大家提供一種方案:如果不希望視圖重繪該怎麼做,請再次仔細看效果圖,我們在FragmentTwo的EditText填寫的內容,用戶點擊返回鍵回來時,內容還在。
FragmentThree.java文件
public class FragmentThree extends Fragment implements OnClickListener {
private Button mBtn;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_three, container, false);
mBtn = (Button) view.findViewById(R.id.id_fragment_three_btn);
mBtn.setOnClickListener(this);
return view;
}
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), " i am a btn in Fragment three",
Toast.LENGTH_SHORT).show();
}
}