Android_Parcelable
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = getIntent(); if (intent != null) { Parcelable p = intent.getParcelableExtra("info"); if (p != null) { System.out.println(p); } } } @Override protected void onDestroy() { super.onDestroy(); } public void start(View view) { Intent intent = new Intent(getApplicationContext(), MainActivity.class); intent.putExtra("info", new Bean(100, "baidu")); startActivity(intent); } }
import android.os.Parcel; import android.os.Parcelable; public class Bean implements Parcelable { int age; String name; public Bean(int age, String name) { this.age = age; this.name = name; } @Override public int describeContents() { // return 0; } @Override public void writeToParcel(Parcel dest, int flags) { //向dest容器中写入数据,int占4个字节,至于区分String应该有特殊的标志位,相当于反序列化 dest.writeInt(this.age); dest.writeString(this.name); } public static final Parcelable.Creator<Bean> CREATOR = new Parcelable.Creator<Bean>() { @Override public Bean createFromParcel(Parcel source) { //按照顺序从source中解析出数据,相当于序列化 int age = source.readInt(); String name = source.readString(); return new Bean(age, name); } @Override public Bean[] newArray(int size) { return new Bean[size]; } }; @Override public String toString() { return "Bean [age=" + age + ", name=" + name + "]"; } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。