9.Activity通过Parcelable方式传递对象
1.下载素材。
本节素材源码,请在公众号回复" AS12071 "。
2.新建AppInfo类。
3.填写AppInfo类信息。
4.编写AppInfo类。
public class AppInfo implements Parcelable {
private String name;
private Double version;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.name);
dest.writeValue(this.version);
}
protected AppInfo(Parcel in) {
this.name = in.readString();
this.version = (Double) in.readValue(Double.class.getClassLoader());
}
public static final Parcelable.Creator<AppInfo> CREATOR = new Parcelable.Creator<AppInfo>() {
@Override
public AppInfo createFromParcel(Parcel source) {
return new AppInfo(source);
}
@Override
public AppInfo[] newArray(int size) {
return new AppInfo[size];
}
};
public AppInfo() {
}
public AppInfo(String name, Double version) {
this.name = name;
this.version = version;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getVersion() {
return version;
}
public void setVersion(Double version) {
this.version = version;
}
}
5.修改MainActivity类。
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) {
//打开SecondActivity
//通过AppInfo对象设置值,进行传递
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
//声明一个AppInfo对象
AppInfo appInfo = new AppInfo("DM盒子",2.3);
//intent传递AppInfo对象
intent.putExtra("appInfo", appInfo);
startActivity(intent);
}
});
}
}
6.修改SecondActivity类。
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//通过getIntent()获取上个Activity传过来的intent
//getParcelableExtra(name名称) 获取AppInfo对象
Intent intent = getIntent();
AppInfo appInfo = (AppInfo) intent.getParcelableExtra("appInfo");
//通过AppInfo对象获取值
String name = appInfo.getName();
Double version = appInfo.getVersion();
//格式化数据
String text = String.format("软件名称:%s,软件版本:%.1f", name, version);
//实例化TextView
TextView textView = findViewById(R.id.textView);
//设置TextView的显示文本
textView.setText(text);
}
}