package com.derry.simplestudy.simple04;
import android.os.Parcel;
import android.os.Parcelable;
public class Student implements Parcelable {
public Student(){}
public String name;
public int age;
protected Student(Parcel in) {
name = in.readString();
age = in.readInt();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<Student> CREATOR = new Creator<Student>() {
@Override
public Student createFromParcel(Parcel in) {
return new Student(in);
}
@Override
public Student[] newArray(int size) {
return new Student[size];
}
};
}
package com.derry.simplestudy.simple04;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.derry.simplestudy.R;
public class MainActivity1 extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
}
public void startAction(View view) {
Intent intent = new Intent(this, MainActivity2.class);
Student student = new Student();
student.name = "DerryOK";
student.age = 33;
intent.putExtra("student", student);
startActivity(intent);
}
}
package com.derry.simplestudy.simple04;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.derry.simplestudy.R;
public class MainActivity2 extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent = getIntent();
Student student = intent.getParcelableExtra("student");
Toast.makeText(this, "student.name:" + student.name
+ " student.age:" + student.age , Toast.LENGTH_SHORT).show();
}
}