Parcelable使用(二)
简单的Activity间数据传递用Intent,复杂的用Parcelable,举个栗子第一个activity写入Parcel的String类型的name和int类型的age,第二个activity取出Parcel并解析数据
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MyPerson mMyPerson = new MyPerson(); mMyPerson.setName("tom"); mMyPerson.setAge(25); Intent mIntent = new Intent(MainActivity.this, Main2Activity.class); Bundle mBundle = new Bundle(); mBundle.putParcelable("key", mMyPerson); mIntent.putExtras(mBundle); startActivity(mIntent); } }); } }
上面是第一个activity
public class Main2Activity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); TextView textView = findViewById(R.id.text); MyPerson parcelable = getIntent().getParcelableExtra("key"); textView.setText("name = " + parcelable.getName() + " age = " + parcelable.getAge()); } }
上面试第二个activity
public class MyPerson implements Parcelable{ private String name; private int age; private static final String TAG = "Text"; 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; } public static final Parcelable.Creator<MyPerson> CREATOR = new Creator<MyPerson>() { @Override public MyPerson createFromParcel(Parcel source) { Log.d(TAG,"createFromParcel"); MyPerson mMyPerson = new MyPerson(); mMyPerson.name = source.readString(); mMyPerson.age = source.readInt(); return mMyPerson; } @Override public MyPerson[] newArray(int size) { // TODO Auto-generated method stub return new MyPerson[size]; } }; @Override public int describeContents() { // TODO Auto-generated method stub Log.d(TAG,"describeContents"); return 0; } @Override public void writeToParcel(Parcel dest, int flags) { // TODO Auto-generated method stub Log.d(TAG,"writeToParcel"); dest.writeString(name); dest.writeInt(age); } }
实现Parcelable接口