Android: Making a class parcelable

后端 未结 5 876
无人及你
无人及你 2020-12-15 06:32

I want to pass on object between two activities in Android which has lead me to parcelable classes. I am not trying to convert my current class but don\'t understand the Par

相关标签:
5条回答
  • 2020-12-15 06:58
    public static final Parcelable.Creator CREATOR =
        new Parcelable.Creator() {
            public ObjectB createFromParcel(Parcel in) {
                return new ObjectB(in);
            }
    
            public ObjectB[] newArray(int size) {
                return new ObjectB[size];
            }
        };
    

    This field is needed for Android to be able to create new objects, individually or as arrays. This also means that you can use use the default constructor to create the object and use another method to hyrdate it as necessary.

    Look at this Android – Parcelable

    Online tool for creating Parcelable class

    and http://www.appance.com/tag/parcelable/

    0 讨论(0)
  • 2020-12-15 06:58

    Here is a great tool for Android parcelable implementations.

    Parcelabler by Dallas Gutauckis

    0 讨论(0)
  • 2020-12-15 07:05

    Here is another tool for creating parcelable objects using simple annotations

    https://github.com/johncarl81/parceler

    0 讨论(0)
  • 2020-12-15 07:06

    Transferring data between activities can be done using serializable as well as Parcelable. But parcelable is considered best.(why)

    There is a plugin in android that lets you insert parcelable code for fields in the class. You can find it from menu File > Settings > Plugins > Android parcelable code generator.

    And use the shortcut alt + insert just like getter and setter to use the plugin.

    0 讨论(0)
  • 2020-12-15 07:10

    On GitHub you can find some code I wrote some time ago for simplifying the handling of Parcelables (e.g. writing to and reading from parcels, simplifying the initializer code for CREATORs).

    Writing to a parcel:

    parcelValues(dest, name, maxSpeed, weight, wheels, color, isDriving);
    

    where color is an enum and isDriving is a boolean, for example.

    Reading from a parcel:

    // [...]
    color = (CarColor)unparcelValue(CarColor.class.getClassLoader());
    isDriving = (Boolean)unparcelValue();
    

    Creating a CREATOR for classes:

    public static final Parcelable.Creator<Car> CREATOR = 
        Parceldroid.getCreatorForClass(Car.class);
    

    ...or for enums:

    public static final Parcelable.Creator<CarColor> CREATOR = 
        Parceldroid.getCreatorForEnum(CarColor.class);
    

    Just take a look at the "ParceldroidExample" I added to the project.

    0 讨论(0)
提交回复
热议问题