編輯:關於 Android 程式設計
為什麼要用 Fragment?最大的好處是在單一 Activity 中就能呈現多種畫面,而且 Fragment 之間的切換動畫變化遠比 Activity 之間豐富。實務上很常見的架構就是一個 Activity 搭配多個 Fragment 輪替。
本文整理 Fragment 與其宿主 Activity 之間的三種資料交換方式,並示範以 FragmentManager 管理堆疊。
1. Fragment 直接取得 Activity 並呼叫其公開方法
((XXXXActivity) getActivity()).fun();
2. Activity 透過 setArguments() 傳值,Fragment 以 getArguments() 接收
3. 定義回呼介面,Fragment 在 onAttach() 中把 Activity 轉型為該介面,需要時再呼叫
三者之中,第一種耦合度最高、最不推薦;第二種適合 Activity → Fragment 的初始資料傳遞;第三種則是 Fragment → Activity 的正規做法。
透過 FragmentManager 管理時,Fragment 的建立與銷毀可以走堆疊模式:
a. FragmentTransaction.add() 推入一個 Fragment;
b. popBackStack() 把它彈出。
這樣使用者按返回鍵時,就能自然回到上一個 Fragment,而不會直接離開 App。
<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"
android:background="#FFFFFFFF"
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.example.testfragment.MainActivity$PlaceholderFragment">
<TextView android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="fragment1" />
<Button android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv"
android:text="跳轉到 Fragment2" />
</RelativeLayout>
package com.example.testfragment;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class MyFragment1 extends Fragment {
FragmentCallBack fragmentCallBack = null;
Button btn;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
btn = (Button) rootView.findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
fragmentCallBack.callbackFun1(null);
}
});
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
fragmentCallBack = (MainActivity) activity;
}
}
<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"
android:background="#FFFFFFFF"
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.example.testfragment.MainActivity$PlaceholderFragment">
<TextView android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="fragment2" />
<Button android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv"
android:text="直接調用 Activity" />
<Button android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btn1"
android:text="回調 Activity" />
</RelativeLayout>
package com.example.testfragment;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class MyFragment2 extends Fragment {
FragmentCallBack fragmentCallBack = null;
Button btn1;
Button btn2;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment2, container, false);
// 取得 Activity 傳來的值
Bundle data = getArguments();
if (data != null) {
Toast.makeText(getActivity(), data.getString("TEXT"), Toast.LENGTH_SHORT).show();
}
btn1 = (Button) rootView.findViewById(R.id.btn1);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 直接調用 Activity 的方法
((MainActivity) getActivity()).changeButtonColor();
}
});
btn2 = (Button) rootView.findViewById(R.id.btn2);
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 以回調方式通知 Activity
fragmentCallBack.callbackFun2(null);
}
});
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
fragmentCallBack = (MainActivity) activity;
}
}
package com.example.testfragment;
import android.os.Bundle;
public interface FragmentCallBack {
void callbackFun1(Bundle arg);
void callbackFun2(Bundle arg);
}
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<Button android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="切換" />
<RelativeLayout android:id="@+id/rl_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@id/btn" />
</RelativeLayout>
package com.example.testfragment;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends ActionBarActivity implements FragmentCallBack {
private Button btn;
private MyFragment1 fragment1;
private MyFragment2 fragment2;
private FragmentManager fragmentManager;
private Fragment currentFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(
android.R.anim.fade_in, android.R.anim.fade_out);
fragment1 = new MyFragment1();
Bundle data = new Bundle();
data.putString("TEXT", "這是 Activity 透過 Bundle 傳遞過來的值");
fragment1.setArguments(data);
fragmentTransaction.add(R.id.rl_container, fragment1);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commitAllowingStateLoss();
currentFragment = fragment1;
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (currentFragment instanceof MyFragment1) {
switchFragment();
} else {
// 目前是 fragment2,出棧即可回到 fragment1
fragmentManager.popBackStack();
currentFragment = fragment1;
}
}
});
}
/** 切換 Fragment */
private void switchFragment() {
if (null == fragment2) {
fragment2 = new MyFragment2();
}
Bundle data = new Bundle();
data.putString("TEXT", "傳遞給 fragment2");
fragment2.setArguments(data);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(
android.R.anim.fade_in, android.R.anim.fade_out);
fragmentTransaction.add(R.id.rl_container, fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commitAllowingStateLoss();
currentFragment = fragment2;
}
public void changeButtonColor() {
btn.setBackgroundColor(Color.RED);
}
@Override
public void callbackFun1(Bundle arg) {
switchFragment();
}
@Override
public void callbackFun2(Bundle arg) {
changeButtonColor();
}
}

初始畫面。

切換到 Fragment2 之後,透過回呼改變按鈕背景的結果。
1. 直接 getActivity() 強轉的做法不推薦。它會讓 Fragment 與特定 Activity 綁死, reused 到其他畫面時容易出問題。若不得已要這麼做,起碼先用 instanceof 判斷型別,並把強轉結果做 null 檢查——getActivity() 在 Fragment 尚未 attach 或已 detach 時會回傳 null。
2. setCustomAnimations 讓切換效果豐富許多。Fragment 切換支援的動畫組合遠多於 Activity 之間的轉場,善用 slide、fade、scale 能顯著提升操作手感。
3. 多個 Fragment 共享一個 Activity,可重複利用大量程式碼。例如共用的 Toolbar、選單、權限請求流程,都只需實作一次。
4. 也可以改用 ViewPager 管理 Fragment。透過 Adapter 掛載多個 Fragment,再以 setCurrentItem() 切換,並同樣以 setArguments() 傳遞資料。這種做法適合可左右滑動的選項卡場景。
5. 幾個容易忽略的細節:
● setArguments() 必須在 Fragment 建立之後、commit 之前呼叫。Fragment 被系統重建時 arguments 會一併還原,因此把參數放在 Bundle 而非依賴 Activity 的成員變數,才能正確走過螢幕旋轉。
● commitAllowingStateLoss() 會在狀態已保存後允許提交,代價是可能丟失這次變更。若非必要,優先行 commitNow() 或確保在生命週期安全點提交。
● onAttach 中轉型的介面引用應在 onDetach 中清空,否則 Fragment 被銷毀後 Activity 的參考仍被持有,容易造成記憶體洩漏。
● 若同時使用 add() 與 hide()/show() 而非 replace(),被隱藏的 Fragment 不會走 onDestroyView,其 View 仍佔用記憶體;在 Fragment 數量多時要留意這點。
百度地圖進階玩法:結合方向傳感器,讓地圖跟著你轉
這一篇要替地圖補上兩件事:一是定位,二是結合方向傳感器,讓地圖能依手機的實際朝向確認方位。有了這兩項,地圖才真正開始「為我所用」。 動手要改的三個地方 整體改動其實集中
startService 啟動過程源碼全解析(Android 6.0)
本文基於 Android 6.0 原始碼,剖析 startService() 背後 ActivityManagerService 所扮演的角色,並釐清 Binder、So
自定義屬性實作帶邊框線的 TextView 控制項
當系統自帶屬性無法滿足需求時,就得替控制項加上自定義屬性。這裡示範一個很典型的例子:讓文字方塊能單獨顯示左、上、右、下任一邊的邊框線。不用自定義屬性當然也做得到,但把「要
Android View 控制元件的事件派發,用實驗一步步推導出來
一直想寫 View 與 ViewGroup 的事件派發流程,這次終於一口氣寫完。猶豫最久的其實是「怎麼寫」——流程性的東西容易變成抄結論,所以我決定用聊天的方式,一邊動手