Skip to content

Commit

Permalink
新文章:parcelable页面间传递实例对象
Browse files Browse the repository at this point in the history
  • Loading branch information
pymongo committed Mar 30, 2020
1 parent 0e4229f commit e4b9625
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 2 deletions.
77 changes: 77 additions & 0 deletions 2020/03/parcelable_serializable.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# [parcelable页面间传递实例对象](/2020/03/parcelable_serializable.md)

Parcelable类似JDK的Serializable接口,用于序列化传输Java实例对象

<!-- tabs:start -->

#### **model**

```java
public static class Product implements Parcelable {
public String name;
public boolean is_purchasable;

/**
* Parcelable序列化
*/
Product(Parcel in) {
name = in.readString();
is_purchasable = in.readByte() != 0;
}

/**
* Parcelable序列化
*/
public static final Creator<Product> CREATOR = new Creator<Product>() {
@Override
public Product createFromParcel(Parcel in) {
return new Product(in);
}

@Override
public Product[] newArray(int size) {
return new Product[size];
}
};

/**
* Parcelable「反」序列化
*/
@Override
public int describeContents() {
return 0;
}

/**
* Parcelable「反」序列化
*/
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
// dest.writeBoolean(is_purchasable);
// writeBoolean是kotlin特有的方法,用不了
dest.writeByte((byte) (is_purchasable ? 1 : 0));
}
}
```

#### **send parcelable**

```java
holder.itemView.setOnClickListener(v -> {
Intent intent = new Intent(v.getContext(), CurrencyDetailActivity.class);
intent.putExtra("product", product);
v.getContext().startActivity(intent);
});
```

#### **receive parcelable**

```java
if (!getIntent().hasExtra("product")) {
return;
}
binding.setProduct(getIntent().getParcelableExtra("product"));
```

<!-- tabs:end -->
3 changes: 1 addition & 2 deletions sidebar.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
- [归档 - 吴翱翔的博客](/)
- **20年3月**
- [parcelable页面间传递实例对象](/2020/03/parcelable_serializable.md)
- [安卓每月小知识积累](/2020/03/monthly_android_note.md)
- [依赖注入](/2020/03/dependency_injection.md)
- [无需定义任何组件id的dataBinding写法](/2020/03/recycler_view_data_binding.md)
Expand Down Expand Up @@ -132,6 +133,4 @@
- [CSS权重等前端豆知识回顾](/unarchived/css_specificity.md)
- **联系我**
- [我的简历](/redirect/resume.html)
- **日记感想**
- [兄弟卧谈会:]()

0 comments on commit e4b9625

Please sign in to comment.