編輯:關於 Android 開發
曾經有段時間,好像聊什麼都能扯到 Fragment,做什麼都要先問一句「Fragment 能不能實現」。玩笑歸玩笑,它確實是理解 Android 適配的一把鑰匙。這篇文章試著把 Fragment 從誕生、生命週期到日常用法一次講完。
Android 跑在手機、平板、電視等各種尺寸的裝置上。過去面對這種差異,常見做法是先做一套手機版 App,再複製一份改佈局去適配大屏——維護成本直接翻倍。Fragment 就是為了終結這種複製貼上而生的。
你可以把 Fragment 想成 Activity 介面上的一個組成單元,一整個 Activity 的畫面甚至可以完全由多個 Fragment 拼裝而成。更關鍵的是,每個 Fragment 擁有自己的生命週期、能獨立接收並處理使用者事件,不必把一堆控件的監聽器全塞進 Activity;而且 Fragment 可以動態加入、替換、移除。
Fragment 依附 Activity 存在,Activity 的生命週期直接牽動 Fragment。相比 Activity,它多出幾個回調:
注意:除 onCreateView 之外,其餘方法若被重寫,都必須呼叫父類的對應實作。
最簡單的方式是把 Fragment 直接寫進 Activity 的佈局檔,步驟只有兩個:繼承 Fragment 並在 onCreateView 決定佈局;在 Activity 佈局中用 <fragment> 標籤宣告。
以下範例用兩個 Fragment 組成一個畫面:上方標題欄、下方內容區。
TitleFragment 的佈局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="45dp"
android:background="@drawable/title_bar" >
<ImageButton
android:id="@+id/id_title_left_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="3dp"
android:background="@drawable/showleft_selector" />
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="我不是微信"
android:textColor="#fff"
android:textSize="20sp" />
</RelativeLayout>
public class TitleFragment extends Fragment {
private ImageButton mLeftMenu;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_title, container, false);
mLeftMenu = (ImageButton) view.findViewById(R.id.id_title_left_btn);
mLeftMenu.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(),
"i am an ImageButton in TitleFragment !",
Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
ContentFragment 的佈局與實作:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="使用 Fragment 做主面板"
android:textSize="20sp" />
</LinearLayout>
public class ContentFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_content, container, false);
}
}
Activity 佈局中直接宣告兩個 Fragment:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="@+id/id_fragment_title"
android:name="com.zhy.zhy_fragments.TitleFragment"
android:layout_width="fill_parent"
android:layout_height="45dp" />
<fragment
android:layout_below="@id/id_fragment_title"
android:id="@+id/id_fragment_content"
android:name="com.zhy.zhy_fragments.ContentFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
把 Fragment 當普通 View 宣告,各自處理自己的事件,Activity 瞬間乾淨了幾倍——可讀性、複用性、可維護性一起提升。
動態用法才是 Fragment 真正的價值所在。調整一下 Activity 佈局:頂部保留標題 Fragment,中間換成 FrameLayout 作為容器,底部放四個切換按鈕。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="@+id/id_fragment_title"
android:name="com.zhy.zhy_fragments.TitleFragment"
android:layout_width="fill_parent"
android:layout_height="45dp" />
<include
android:id="@+id/id_ly_bottombar"
android:layout_width="fill_parent"
android:layout_height="55dp"
android:layout_alignParentBottom="true"
layout="@layout/bottombar" />
<FrameLayout
android:id="@+id/id_content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="@id/id_ly_bottombar"
android:layout_below="@id/id_fragment_title" />
</RelativeLayout>
public class MainActivity extends Activity implements OnClickListener {
private LinearLayout mTabWeixin;
private LinearLayout mTabFriend;
private ContentFragment mWeixin;
private FriendFragment mFriend;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mTabWeixin = (LinearLayout) findViewById(R.id.tab_bottom_weixin);
mTabFriend = (LinearLayout) findViewById(R.id.tab_bottom_friend);
mTabWeixin.setOnClickListener(this);
mTabFriend.setOnClickListener(this);
setDefaultFragment();
}
private void setDefaultFragment() {
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
mWeixin = new ContentFragment();
transaction.replace(R.id.id_content, mWeixin);
transaction.commit();
}
@Override
public void onClick(View v) {
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
switch (v.getId()) {
case R.id.tab_bottom_weixin:
if (mWeixin == null) {
mWeixin = new ContentFragment();
}
transaction.replace(R.id.id_content, mWeixin);
break;
case R.id.tab_bottom_friend:
if (mFriend == null) {
mFriend = new FriendFragment();
}
transaction.replace(R.id.id_content, mFriend);
break;
}
transaction.commit();
}
}
FriendFragment 的實作與 ContentFragment 幾乎一樣,只是載入不同佈局:
public class FriendFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_friend, container, false);
}
}
補充一點:若專案要支援 Android 3.0 以下版本,需引入 support-v4 套件,Activity 改繼承 FragmentActivity,並透過 getSupportFragmentManager() 取得 FragmentManager。不過更建議把 Manifest 中 uses-sdk 的 minSdkVersion 與 targetSdkVersion 都設在 11 以上,就能直接用原生 API。
android.app.Fragment:用來定義 Fragment 本身。android.app.FragmentManager:在 Activity 中操作 Fragment。android.app.FragmentTransaction:保證一系列 Fragment 操作的原子性。取得 FragmentManager:getFragmentManager()(v4 套件中為 getSupportFragmentManager())。開啟事務:fm.beginTransaction()。
常有人遇到 State loss 之類的狀態不一致錯誤,根因通常是:commit() 一定要在 Activity.onSaveInstanceState() 之前呼叫。
想保留使用者的操作內容(例如在 FragmentA 的 EditText 打了字,切到 B 再切回來還要看得到),用 hide() 與 show()。切記別每次都 new 新實例,記得做 null 判斷。
不打算保留操作狀態,用 remove() + add(),或直接 replace(),兩者效果相同。
remove 與 detach 的差別:不考慮回退棧的前提下,remove() 會銷毀整個 Fragment 實例,detach() 只銷毀視圖結構、實例仍在。若宿主 Activity 長期存在,又不需要保留操作狀態,優先選 detach() 更省資源。
把生命週期搞清楚了,那些曾經覺得 Fragment「問題一堆」的時刻,多半都能回溯到某個方法究竟銷毀了視圖、銷毀了實例,還是只是藏了起來。
由於篇幅關係,回退棧管理、Fragment 與 Activity 的互動最佳實踐、無佈局 Fragment 的用途、用 Fragment 建立對話框、以及與 ActionBar / MenuItem 整合,留待下一篇。
Fragment 的兩種添加方式:XML 靜態聲明與代碼動態加載
Fragment 的兩種添加方式:XML 靜態聲明與代碼動態加載 Fragment 可以理解為 Activity 界面中的一個「行為單元」或界面片段。借助 Fragmen
Android 提高 21 篇之十:用 AudioRecord 打造簡易助聽器
在 Android 音訊開發中,錄音與播放常是兩個相互配合的環節。相較於 MediaRecorder 會直接將麥克風資料編碼並存檔,AudioRecord 更適合取得即時
Android 開機自啟動實作:BOOT_COMPLETED 廣播與 SharedPreferences 開關
實作思路 開機自啟動的核心是 BOOT_COMPLETED 這個系統廣播。開機完成後系統會發出它,應用只要註冊接收就能被喚醒。至於「要不要自啟動」,則交給使用者透過設定介
Android 自定義 View(一):自繪控件入門,掌握 onDraw 與 Canvas/Paint
先坦白說,我對自定義 View 的理解還很淺。最近啃了幾天 guolin 博主關於自定義 View 的系列文章,寫得非常精彩,只是涉及原始碼與底層的內容讓我一時有點發懵。