Android - Implementing Parcelable Inner Class

前端 未结 1 1676
梦谈多话
梦谈多话 2021-01-29 02:59

I know how to implement a simple Parcelable class with public variables but the class below is somewhat more complex. How can I implement the Parcelable interface given that thi

相关标签:
1条回答
  • 2021-01-29 03:52

    You simply need to implement the Parcelable interface for each inner class (ListEntity, SysEntity, ...), so all classes and classes they contain implement Parcelable.

    Then you add the class to the parcel using

    public final void writeParcelable (Parcelable p, int parcelableFlags)
    

    where p is the instance of your inner class.

    Edit: here's an example of how to parcel an inner class:

    public class SampleParcelable implements Parcelable {
        public static class InnerClass implements Parcelable {
            private String mInnerString;
            private long mInnerLong;
    
            // parcelable interface
            @Override
            public int describeContents() {
                return 0;
            }
    
            @Override
            public void writeToParcel(Parcel dest, int flags) {
                dest.writeString(mInnerString);
                dest.writeLong(mInnerLong);
            }
    
            public static final Creator<InnerClass> CREATOR = new Creator<InnerClass>() {
                public InnerClass createFromParcel(Parcel in) {
                    return new InnerClass(in);
                }
    
                public InnerClass[] newArray(int size) {
                    return new InnerClass[size];
                }
            };
    
            private InnerClass(Parcel in) {
                mInnerString = in.readString();
                mInnerLong = in.readLong();
            }
        }
    
        private String mString;
        private long mLong;
        private InnerClass mInnerClass;
    
        // parcelable interface
        @Override
        public int describeContents() {
            return 0;
        }
    
        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeString(mString);
            dest.writeLong(mLong);
            dest.writeParcelable(mInnerClass, flags);
        }
    
        public static final Creator<SampleParcelable> CREATOR = new Creator<SampleParcelable>() {
            public SampleParcelable createFromParcel(Parcel in) {
                return new SampleParcelable(in);
            }
    
            public SampleParcelable[] newArray(int size) {
                return new SampleParcelable[size];
            }
        };
    
        private SampleParcelable(Parcel in) {
            mString = in.readString();
            mLong = in.readLong();
            mInnerClass = in.readParcelable(InnerClass.class.getClassLoader());
        }
    }
    
    0 讨论(0)
提交回复
热议问题