android:intent传递对象(Parcelable)
一,代码:
1,所传递对象的类
package com.example.okdemo1.model;
import android.os.Parcel;
import android.os.Parcelable;
public class Goods3 implements Parcelable {
//商品id
private int id;
//商品名称
private String name;
public Goods3(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static final Creator<Goods3> CREATOR = new Creator<Goods3>() {
@Override
public Goods3 createFromParcel(Parcel in) {
Goods3 g3 = new Goods3(in.readInt(),in.readString());
return g3;
}
@Override
public Goods3[] newArray(int size) {
return new Goods3[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(name);
}
}
2,发送对象:
//给按钮增加点击事件
Button myButton = findViewById(R.id.apibutton);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 处理点击事件
Intent intent = new Intent(MainActivity.this, PreferenceActivity.class);
Goods3 three = new Goods3(13,"苏东坡新传");
// 增加要传递的参数
intent.putExtra("three", three); // 传递字符串数据
startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(MainActivity.this).toBundle());
System.out.println("点击完成");
}
});
3,接收对象:
public class PreferenceActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_preference);
//接收参数
Intent intent = getIntent();
Goods3 three = (Goods3)intent.getParcelableExtra("three");
Log.d("参数",three.getName());
Log.d("参数",String.valueOf(three.getId()));
}
}
二,测试效果:

浙公网安备 33010602011771号