gpt4 book ai didi

java - 如何将 Parcelable 与 setter 和 getter 一起使用?

转载 作者:行者123 更新时间:2023-12-01 23:44:37 25 4
gpt4 key购买 nike

我使用 Parcelable 实现,因为使用 putParcelableArrayListExtra 传递 ArrayList 更容易,但是 protected Song(Parcel in) and public void writeToParcel(Parcel dest, int flags) 的目的是什么?

我的可分割类

public class Song implements Parcelable {

private long id = 0;
private String data = "";
private String title = "";
private String artist = "";

public Song(){
}

protected Song(Parcel in) {
id = in.readLong();
data = in.readString();
title = in.readString();
artist = in.readString();
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeString(data);
dest.writeString(title);
dest.writeString(artist);
}

public void setId(long songId){ this.id = songId; }
public long getId(){
return id;
}
public void setData(String data) { this.data = data; }
public String getData(){return data;}

//Optional meta data

public void setTitle(String title){ this.title = title; }
public String getTitle() { return title; }

public void setArtist(String artist){
this.artist = artist;
}
public String getArtist() {
return artist;
}

对于它的用途,如果我没有向我的 Song() 构造函数传递任何参数,我是否还需要添加它,或者我可以将其留空吗?

protected Song(Parcel in) {
id = in.readLong();
data = in.readString();
title = in.readString();
artist = in.readString();
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeString(data);
dest.writeString(title);
dest.writeString(artist);
}

最佳答案

我们需要这个方法,因为它会覆盖方法,并且如果您不删除它并手动创建 setter 和 getter,那么 getter 和 setter 将自动工作

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeString(data);
dest.writeString(title);
dest.writeString(artist);
}

关于java - 如何将 Parcelable 与 setter 和 getter 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58245879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com