Android, Can I use putExtra to pass multiple values

前端 未结 6 1584
北恋
北恋 2020-12-02 06:54

I want to pass two values to another activity can I do this with putExtra or do I have to do it a more complicated way, which it seems from my reading. E.g.. can something l

6条回答
  •  生来不讨喜
    2020-12-02 07:22

    For a single small amount of value putExtra is perfect but when you pass multiple values and need to pass custom ArrayList or List then I think it's a bad idea. Solution is you can use Parcelable. You and also use Singleton or Serializable also.

    Parcelable:

    Parcelable class which you need to share.

     public class MyParcelable implements Parcelable {
         private int mData;
    
         public int describeContents() {
             return 0;
         }
    
         public void writeToParcel(Parcel out, int flags) {
             out.writeInt(mData);
         }
    
         public static final Parcelable.Creator CREATOR
                 = new Parcelable.Creator() {
             public MyParcelable createFromParcel(Parcel in) {
                 return new MyParcelable(in);
             }
    
             public MyParcelable[] newArray(int size) {
                 return new MyParcelable[size];
             }
         };
    
         private MyParcelable(Parcel in) {
             mData = in.readInt();
         }
     }
    

    Form your activity where you want to send

    MyParcelable example = new MyParcelable();
    .....
    .....
    Bundle bundle = new Bundle();
    bundle.putParcelable("example", Parcels.wrap(example));
    

    From another activity where you want to receive

    MyParcelable example = Parcels.unwrap(getIntent().getParcelableExtra("example"));
    

提交回复
热议问题