編輯:關於 Android 開發
頁面跳轉時如何把數據帶過去,是 Activity 開發中的基礎問題。本文梳理 Bundle、Intent 以及 Parcelable / Serializable 對象傳遞的具體做法。
先看效果圖:

Bundle 用作數據載體,使用方式類似 Map,用於存放 key-value 形式的值。相比 Map,它針對常用類型提供了成套的 putXxx() / getXxx() 方法,例如 putString() / getString()、putInt() / getInt()。其內部實際上是用 HashMap<String, Object> 來存儲數據。
簡單說,Bundle 就是一個專門用於配合 Intent 傳值的「打包容器」。
寫法一:批量添加。先把數據裝進 Bundle,再一次性掛到 Intent 上:
Intent intent = new Intent();
Bundle bundle = new Bundle(); // 該類用作攜帶數據
bundle.putString("name", "Alice");
bundle.putInt("age", 20);
// 為意圖追加額外數據。意圖原有的數據不會丟失,
// 但 key 同名的數據會被替換
intent.putExtras(bundle);
寫法二:逐個添加。直接調用 Intent 的 putExtra():
Intent intent = new Intent();
intent.putExtra("name", "XXX");
兩者有區別嗎?完全沒有。當你調用 putExtras() 時,傳入的 Bundle 會被轉換為 Intent 的鍵值數據(Intent 本身也是以鍵值模式承載數據的)。寫法二在只需傳少量數據時更簡潔,寫法一則在數據較多、需要復用 Bundle 時更清晰。
接收方直接使用 getIntent() 拿到傳入的 Intent,再調用 getExtras() 取出 Bundle,然後按需 get 即可:
Bundle bundle = getIntent().getExtras();
String str = bundle.getString("USERNAME"); // 取鍵為 USERNAME 的字符串
int num = bundle.getInt("Number"); // 取鍵為 Number 的整型
Android 組件間傳遞對象時,推薦實現 Parcelable 接口;也可以使用 Java 原生的 Serializable 接口。前者是 Android 專門設計的序列化方案,內存與性能表現明顯優於後者,數據量越大差距越明顯。
1. 讓實體類實現 Parcelable:
public class ParcelableData implements Parcelable {
private String name;
private int age;
public ParcelableData() {
name = "guest";
age = 20;
}
// 從 Parcel 中讀取,順序必須與 writeToParcel 的寫入順序完全一致
protected ParcelableData(Parcel in) {
name = in.readString();
age = in.readInt();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
}
public static final Parcelable.Creator<ParcelableData> CREATOR =
new Parcelable.Creator<ParcelableData>() {
public ParcelableData createFromParcel(Parcel in) {
return new ParcelableData(in);
}
public ParcelableData[] newArray(int size) {
return new ParcelableData[size];
}
};
}
這裡最容易犯的低級錯誤是讀寫順序不一致——writeToParcel() 中先寫 name 後寫 age,那麼構造函數中就必須先讀 name 後讀 age,否則數據會錯位。
2. 發送對象:Bundle 本身也實現了 Parcelable 接口,實戰中通常通過 Bundle 封裝數據再傳送。
Intent intent = new Intent();
intent.setClass(this, SubActivity.class);
// 方式一:直接附加 Parcelable 對象
// intent.putExtra("MyData", new ParcelableData());
// 方式二:通過 Bundle 封裝(推薦,可同時攜帶多個值)
Bundle bundle = new Bundle();
bundle.putString("MyString", "test bundle");
bundle.putParcelable("MyData", new ParcelableData());
intent.putExtras(bundle);
startActivity(intent);
3. 接收對象:
// 方式一:直接從 Intent 中取
// ParcelableData data = getIntent().getParcelableExtra("MyData");
// 方式二:先取 Bundle,再從中解析
Bundle bundle = getIntent().getExtras();
ParcelableData parcelableData = bundle.getParcelable("MyData");
String testBundleString = bundle.getString("MyString");
Log.v("string=", testBundleString);
Log.v("name=", parcelableData.getName());
Log.v("age=", String.valueOf(parcelableData.getAge()));
public class TestBundleActivity extends AppCompatActivity {
EditText editText1;
EditText editText2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_bundle);
editText1 = (EditText) findViewById(R.id.editText1);
editText2 = (EditText) findViewById(R.id.editText2);
}
/** 提交選擇的地區,把字符串傳給 TestBundleActivity3 */
public void submitRegion(View view) {
EditText editTextRegion = (EditText) findViewById(R.id.editTextRegion);
Intent intent = new Intent(this, TestBundleActivity3.class);
String region = editTextRegion.getText().toString();
if (!TextUtils.isEmpty(region)) {
intent.putExtra("region", region);
startActivity(intent);
} else {
Toast.makeText(this, "地區不能是空值", Toast.LENGTH_SHORT).show();
}
}
/** 兩個 Integer 相加,傳入 TestBundleActivity1 計算 */
public void calculte(View view) {
Intent intent = new Intent(this, TestBundleActivity1.class);
Bundle bundle = new Bundle();
String first = editText1.getText().toString();
String second = editText2.getText().toString();
if (!TextUtils.isEmpty(first) && !TextUtils.isEmpty(second)) {
bundle.putInt("first", Integer.parseInt(first));
bundle.putInt("second", Integer.parseInt(second));
intent.putExtras(bundle);
startActivity(intent);
} else {
Toast.makeText(this, "數值不能是空", Toast.LENGTH_SHORT).show();
}
}
/** 傳遞 Serializable 對象到 TestBundleActivity2 */
public void login(View view) {
EditText editTextName = (EditText) findViewById(R.id.editTextName);
EditText editTextCode = (EditText) findViewById(R.id.editTextCode);
Intent intent = new Intent(this, TestBundleActivity2.class);
Bundle bundle = new Bundle();
String name = editTextName.getText().toString();
String code = editTextCode.getText().toString();
if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(code)) {
Person person = new Person();
person.setName(name);
person.setCode(code);
bundle.putSerializable("person", person);
intent.putExtras(bundle);
startActivity(intent);
} else {
Toast.makeText(this, "姓名編號不能是空", Toast.LENGTH_SHORT).show();
}
}
}
Intent 攜帶的數據會經歷序列化與跨進程拷貝,系統對 Bundle 大小存在實際限制(歷史上大致在 1MB 量級,具體與 Binder 緩衝區相關)。因此:
示例整理自「安卓無憂」學習項目,可在應用寶或豌豆莢下載完整源碼對照參考。
Eclipse 找不到 Annotation Processing 設定的解法:補齊 JDT 然后他才能出現
在 Eclipse 中開發時,若/preferences 底下的 Java Compiler 裡找不到 Annotation Processing 相關選項,通常不是設定
Android 音樂播放器:Open Core 與 MediaPlayer 入門
Open Core 與 Android 多媒體框架 Open Core 是 Android 多媒體框架的核心,負責音訊與視訊的播放、下載、編碼與解碼。無論是音樂播放器、影
Android Studio 記憶體不足?調整 studio64.exe.vmoptions 的實用方法
記憶體不足的可能原因 Android Studio 效能低落或提示記憶體不足,可能來自電腦記憶體不足、開啟太多程式、專案過大,或 IDE 本身分配的堆大小太小。 調整方
Android加固教程:先學會破解,用IDA動態調試修改內存改寫程式走向
Android加固教程:先學會破解,用IDA動態調試修改內存改寫程式走向 【版權所有,轉載請註明出處。】 因公司專案需要對app進行加固,經過數月研究,我實現了一套完整的