美文网首页
Android枚举实现Parcelable接口

Android枚举实现Parcelable接口

作者: zivxia | 来源:发表于2016-12-11 19:26 被阅读1237次

    枚举类实现Parcelable的写法如下:

    public enum MyEnum implements Parcelable {    
    
           FIRST(1), SECOND(2);    
    
           private int mValue;    
    
           MyEnum(int value) {        
                 this.mValue = value;   
            }    
    
            @Override    
            public void writeToParcel(Parcel dest, int flags) {     
                  dest.writeInt(mValue);    
            }   
     
            @Override    
            public int describeContents() {        
                  return 0;    
            }   
     
            public static final Creator<MyEnum> CREATOR = new Creator<MyEnum>() {        
                    @Override        
                     public MyEnum createFromParcel(Parcel in) {     
                         return MyEnum.values()[in.readInt()];       
             }    
        
            @Override        
            public MyEnum[] newArray(int size) {            
                   return new MyEnum[size];        
                  }    
            };
    }
    

    当枚举类为一个类的成员变量,并且该类也要实现Parcelable接口时,则先让枚举类实现Parcelable接口,

    public class MyClass implements Parcelable {   
     
         private String name;    
    
         private int age;    
    
        private MyEnum myEnum;  
      
        protected MyClass(Parcel in) {        
            name = in.readString();        
            age = in.readInt();        
            myEnum = in.readParcelable(MyEnum.class.getClassLoader()); 
       }    
    
        @Override    
        public void writeToParcel(Parcel dest, int flags) {   
            dest.writeString(name);        
            dest.writeInt(age);        
            dest.writeParcelable(myEnum, flags);   
         }    
        @Override   
       public int describeContents() {        
            return 0;    
       }  
      
      public static final Creator<MyClass> CREATOR = new Creator<MyClass>() {        
          @Override        
          public MyClass createFromParcel(Parcel in) {            
              return new MyClass(in);        
          }        
          @Override        
          public MyClass[] newArray(int size) {            
            return new MyClass[size];        
           }    
        };
    }
    
    

    相关文章

      网友评论

          本文标题:Android枚举实现Parcelable接口

          本文链接:https://www.haomeiwen.com/subject/pxppmttx.html