Android 高手進(jìn)階教程:[15]傳遞對象方法
在 Android 開發(fā)中,數(shù)據(jù)傳遞是一個非常重要的環(huán)節(jié)。無論是從一個 Activity 傳遞到另一個 Activity,還是在同一個 Activity 中的不同 Fragment 之間共享數(shù)據(jù),掌握正確的傳遞對象的方法都是必不可少的技能。本文將深入探討幾種常見的對象傳遞方式,并結(jié)合實(shí)際案例幫助你更好地理解和應(yīng)用這些技術(shù)。
1. 使用 Intent 傳遞對象
Intent 是 Android 中用于在不同組件之間傳遞數(shù)據(jù)的核心機(jī)制之一。對于簡單的數(shù)據(jù)類型(如字符串、整數(shù)等),可以直接通過 putExtra() 方法添加到 Intent 中。然而,當(dāng)需要傳遞自定義對象時,則需要確保該對象實(shí)現(xiàn)了 Serializable 或 Parcelable 接口。
實(shí)現(xiàn) Serializable 接口
```java
public class Person implements Serializable {
private String name;
private int age;
// 構(gòu)造函數(shù)與 getter/setter 省略
}
```
然后,在發(fā)送方:
```java
Person person = new Person("John", 30);
Intent intent = new Intent(this, TargetActivity.class);
intent.putExtra("person", person);
startActivity(intent);
```
接收方可以通過 getIntent().getSerializableExtra() 獲取對象:
```java
Person receivedPerson = (Person) getIntent().getSerializableExtra("person");
```
使用 Parcelable 接口
相比 Serializable,Parcelable 提供了更高的性能,尤其是在大量數(shù)據(jù)傳遞時。以下是實(shí)現(xiàn)步驟:
```java
public class Person implements Parcelable {
private String name;
private int age;
protected Person(Parcel in) {
name = in.readString();
age = in.readInt();
}
public static final Creator
@Override
public Person createFromParcel(Parcel in) {
return new Person(in);
}
@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
}
}
```
發(fā)送和接收過程類似,只是需要使用 putParcelable 和 getParcelableExtra。
2. 使用 Bundle 和 BundleCompat
Bundle 是一種輕量級的數(shù)據(jù)容器,常用于存儲鍵值對。通過 BundleCompat,即使在低版本 Android 上也能安全地使用 Bundle 進(jìn)行跨進(jìn)程通信。
示例代碼:
```java
Bundle bundle = new Bundle();
bundle.putParcelable("person", person);
TargetActivity.startActivity(bundle);
```
3. ViewModel 的應(yīng)用
ViewModel 是一種設(shè)計模式,特別適用于保存 UI 相關(guān)的狀態(tài)信息。通過 ViewModel,可以在多個 Fragment 或 Activity 之間共享數(shù)據(jù),而無需手動管理生命周期。
創(chuàng)建 ViewModel:
```java
public class SharedViewModel extends ViewModel {
private final MutableLiveData
public void select(Person person) {
selected.setValue(person);
}
public LiveData
return selected;
}
}
```
在 Fragment 或 Activity 中注入 ViewModel 并監(jiān)聽變化:
```java
SharedViewModel model = new ViewModelProvider(this).get(SharedViewModel.class);
model.getSelected().observe(this, person -> {
// 處理接收到的對象
});
```
總結(jié)
以上介紹了三種常見的對象傳遞方式:Intent 的 Serializable 和 Parcelable、Bundle 及其兼容性處理,以及 ViewModel 的應(yīng)用。每種方法都有其適用場景,開發(fā)者應(yīng)根據(jù)具體需求選擇最合適的方案。希望本文能為你的 Android 開發(fā)之路提供有力的支持!
如果您有任何疑問或需要進(jìn)一步的幫助,請隨時告訴我!