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

前端 未结 15 1009
时光取名叫无心
时光取名叫无心 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:11

    You can make your enum implement Parcelable which is quite easy for enums:

    public enum MyEnum implements Parcelable {
        VALUE;
    
    
        @Override
        public int describeContents() {
            return 0;
        }
    
        @Override
        public void writeToParcel(final Parcel dest, final int flags) {
            dest.writeInt(ordinal());
        }
    
        public static final Creator CREATOR = new Creator() {
            @Override
            public MyEnum createFromParcel(final Parcel source) {
                return MyEnum.values()[source.readInt()];
            }
    
            @Override
            public MyEnum[] newArray(final int size) {
                return new MyEnum[size];
            }
        };
    }
    

    You can then use Intent.putExtra(String, Parcelable).

    UPDATE: Please note wreckgar's comment that enum.values() allocates a new array at each call.

    UPDATE: Android Studio features a live template ParcelableEnum that implements this solution. (On Windows, use Ctrl+J)

提交回复
热议问题