一、Fragment詳解
1. 什麼是Fragment ?
你可以簡單的理解爲,Fragment是顯示在Activity中的Activity。它可以顯示在Activity中,然後它也可以顯示出一些內容。因爲它擁有自己的生命週期,可以接受處理用戶的事件,並且你可以在一個Activity中動態的添加,替換,移除不同的
Fragment,因此對於信息的展示具有很大的便利性。
2. Fragment的生命週期
因爲Fragment是依附於Activity存在的,因此它的生命週期受到Activity的生命週期影響
Fragment比Activity多了幾個生命週期的回調方法
- onAttach(Activity) 當Fragment與Activity發生關聯的時候調用
- onCreateView(LayoutInflater, ViewGroup, Bundle) 創建該Fragment的視圖
- onActivityCreated(Bundle) 當Activity的onCreated方法返回時調用
- onDestroyView() 與onCreateView方法相對應,當該Fragment的視圖被移除時調用
- onDetach() 與onAttach方法相對應,當Fragment與Activity取消關聯時調用
3. Fragment的使用方式
靜態使用Fragment
步驟:① 創建一個類繼承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對象中,並填充到此Fragment中
* */
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>
動態使用Fragment
實現點擊不同的按鈕,在Activity中顯示不同的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>
繼承Fragment2的類
public class MyFragment 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);
}
}
① 在Acitivity對應的佈局中寫上一個FramLayout控件,此空間的作用是當作Fragment的容器,Fragment通過FrameLayout顯示在Acitivity裏,這兩個單詞容易混淆,請注意
② 準備好你的Fragment,然後再Activity中實例化,v4包的Fragment是通過getSupportFragmentManager()方法新建Fragment管理器對象,此處不討論app包下的Fragment
③ 然後通過Fragment管理器對象調用beginTransaction()方法,實例化FragmentTransaction對象,有人稱之爲事務
④ FragmentTransaction對象【以下直接用transaction代替】,transaction的方法主要有以下幾種:
- 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() 提交事務
注意:在add/replace/hide/show以後都要commit其效果纔會在屏幕上顯示出來
4. 什麼是Fragment的回退棧?
Fragment的回退棧是用來保存每一次Fragment事務發生的變化 如果你將Fragment任務添加到回退棧,當用戶點擊後退按鈕時,將看到上一次的保存的Fragment。一旦Fragment完全從後退棧中彈出,用戶再次點擊後退鍵,則退出當前Activity
首先來看一下這個東西:
1.首先顯示第一個FragmentOne頁面有一個Button in FragmentOne,上面有個輸入框顯示的是Fragment One
2.然後輸入change,點擊Button in FragmentOne,然後顯示第二個Fragment,裏面有一個Button in FragmentTwo,一個輸入框顯示Fragment Two
3.輸入change,點擊按鈕,顯示第三個Fragment,上面有個Button inFragmentThree,點擊按鈕顯示出一個Toast
4.【注意】點擊返回鍵,跳轉到前一個FragmentTwo,這個時候可以看到上面的輸入框中顯示的是Fragment Two change,也就是說保留了我們離開這個Fragment時候他所呈現的狀態
5.【注意】再點擊返回鍵,跳轉到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包下的】Fragment詳解
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();
}
}
Fragment的點擊事件裏寫的是replace方法,相當於remove和add的合體,並且如果不添加事務到回退棧,前一個Fragment實例會被銷燬。這裏很明顯,我們調用tx.addToBackStack(null)將當前的事務添加到了回退棧,所以FragmentOne實例不會被銷燬,但是視圖層次依然會被銷燬,即會調用onDestoryView和onCreateView。所以【請注意】,當之後我們從FragmentTwo返回到前一個頁面的時候,視圖層仍舊是重新按照代碼繪製,這裏僅僅是是實例沒有銷燬,因此顯示的頁面中沒有change幾個字。
FragmentTwo.class文件
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, cont
ainer, false);
mBtn = (Button) view.findViewById(R.id.id_fragment_two_b
tn);
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.replace(R.id.id_content, fThree, "THREE");
tx.addToBackStack(null);
tx.commit();
}
}
這裏點擊時,我們沒有使用replace,而是先隱藏了當前的Fragment,然後添加了FragmentThree的實例,最後將事務添加到回退棧。這樣做的目的是爲了給大家提供一種方案:如果不希望視圖重繪該怎麼做,請再次仔細看效果圖,我們在FragmentTwo的EditText填寫的內容,用戶點擊返回鍵回來時,內容還在。
FragmentThree.class文件
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, co
ntainer, 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 t
hree",Toast.LENGTH_SHORT).show();
}
}
5. Fragment與Activity之間的通信
Fragment依附於Activity存在,因此與Activity之間的通信可以歸納爲以下幾點:
如果你Activity中包含自己管理的Fragment的引用,可以通過引用直接訪問所有的Fragment的public方法
如果Activity中未保存任何Fragment的引用,那麼沒關係,每個Fragment都有一個唯一的TAG或者ID,可以通過getFragmentManager.findFragmentByTag()或者findFragmentById()獲得任何Fragment實例,然後進行操作
Fragment中可以通過getActivity()得到當前綁定的Activity的實例,然後進行操作。