这种方式的实现原理是将一个完整的对象进行分解,而分解后的每一部分都是Intent所支持的数据类型,这样也就实现传递对象的功能了。
接下来看下例子
首先是先设定一个类,水果类,然后implements Parcelable:
package com.example.parcelableapplication; import android.os.Parcel; import android.os.Parcelable; public class Fruit implements Parcelable { private String name; private int price; public Fruit() { } protected Fruit(Parcel in) { name = in.readString(); price = in.readInt(); } public static final Parcelable.Creator<Fruit> CREATOR = new Parcelable.Creator<Fruit>() { @Override public Fruit createFromParcel(Parcel source) { Fruit fruit = new Fruit(); fruit.name = source.readString(); fruit.price = source.readInt(); return fruit; } @Override public Fruit[] newArray(int size) { return new Fruit[size]; } }; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); dest.writeInt(price); } }
然后在MainActivity:
package com.example.parcelableapplication; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { private EditText edt,edt_age; private Button btn ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edt = findViewById(R.id.edt); edt_age = findViewById(R.id.edt_age); btn = findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name = edt.getText().toString(); int price = Integer.parseInt(edt_age.getText().toString()); Fruit fruit = new Fruit(); fruit.setName(name); fruit.setPrice(price); Intent intent = new Intent(MainActivity.this,SecondActivity.class); intent.putExtra("Fruit_data",fruit); startActivity(intent); } }); } }
然后是SecondActivity:
package com.example.parcelableapplication; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; public class SecondActivity extends AppCompatActivity { private TextView txt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); txt = findViewById(R.id.txt); Fruit fruit = (Fruit)getIntent().getParcelableExtra("Fruit_data"); String name = fruit.getName(); float price = fruit.getPrice(); txt.setText("水果名: "+ name +"; 价格:"+price); } }