简体   繁体   English

如何将 parcelable 与 setter 和 getter 一起使用?

[英]How to use parcelable with setters and getters?

I'm using the parcelable implemenation because it's easier to pass an ArrayList with putParcelableArrayListExtra , but what is the purpose of protected Song(Parcel in) and public void writeToParcel(Parcel dest, int flags)我正在使用 parcelable 实现,因为使用putParcelableArrayListExtra传递 ArrayList 更容易,但是protected Song(Parcel in) and public void writeToParcel(Parcel dest, int flags)的目的是什么

My parcelable class我的可包裹 class

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;
    }

For what is this used, do i still need to add this if i'm not passing any parameters to my Song() constructor or can i just leave it empty?对于它的用途,如果我没有将任何参数传递给我的 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);
        }

We need this method because it overrides method and with the help getter and setter will work automatically if you don't remove this and manually make setter & getter我们需要这个方法,因为它覆盖了方法,并且如果你不删除它并手动制作 setter 和 getter,getter 和 setter 将自动工作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM