Passing enum or object through an intent (the best solution)

前端 未结 15 925
时光取名叫无心
时光取名叫无心 2020-12-04 05:41

I have an activity that when started needs access to two different ArrayLists. Both Lists are different Objects I have created myself.

Basically I need a way to pa

15条回答
  •  無奈伤痛
    2020-12-04 06:13

    If you really need to, you could serialize an enum as a String, using name() and valueOf(String), as follows:

     class Example implements Parcelable { 
       public enum Foo { BAR, BAZ }
    
       public Foo fooValue;
    
       public void writeToParcel(Parcel dest, int flags) {
          parcel.writeString(fooValue == null ? null : fooValue.name());
       }
    
       public static final Creator CREATOR = new Creator() {
         public Example createFromParcel(Parcel source) {        
           Example e = new Example();
           String s = source.readString(); 
           if (s != null) e.fooValue = Foo.valueOf(s);
           return e;
         }
       }
     }
    

    This obviously doesn't work if your enums have mutable state (which they shouldn't, really).

提交回复
热议问题