Activity传递的Parcelable并不是同一个对象

网上清一色的说Activity之间通过parcel传递对象,但是其实这并不是同一个对象。

我不知道是我理解错了还是怎么回事?希望看到文章的人点评一下

class MyParcelable implements Parcelable {
    private static final String TAG = "TestActivity";
    private String username;
    private String nickname;

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getNickname() {
        return nickname;
    }
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    protected MyParcelable() {

    }

    public MyParcelable(String username, String nickname) {
        super();
        this.username = username;
        this.nickname = nickname;
        Log.d(TAG, "MyParcelable(String username, String nickname)");
    }

    protected MyParcelable(Parcel in) {
        username = in.readString();
        nickname=in.readString();
        Log.d(TAG, "MyParcelable(Parcel in)");
    }

    public static final Creator CREATOR = new Creator() {
        @Override
        public MyParcelable createFromParcel(Parcel in) {
            Log.d(TAG, "createFromParcel(Parcel in)");
            //这里明明新建了一个对象
            //
            return new MyParcelable(in);
        }

        @Override
        public MyParcelable[] newArray(int size) {
            Log.d(TAG, "newArray(int size)");
            return new MyParcelable[size];
        }
    };

    @Override
    public int describeContents() {
        Log.d(TAG, "describeContents()");
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(username);
        parcel.writeString(nickname);
        Log.d(TAG, "writeToParcel(Parcel parcel, int i)");
    }

 

//主Activity

Intent intent = new Intent();
        intent.setClass(this, TestActivity2.class);
        Bundle bundle = new Bundle();
        MyParcelable data = new MyParcelable("cfc", "cfcnick");
        Log.d(TAG, "data="+data); //这两处不是同一个地址
        bundle.putParcelable("test", data);
//        intent.putExtras(bundle);
        intent.putExtra("test", data);
        startActivity(intent);

 

//跳转到Activity

Intent intent = getIntent();
MyParcelable data = intent.getParcelableExtra("test");
Log.i(TAG, "data="+data.getUsername()+","+data.getNickname());
Log.d(TAG, "data="+data); //这两处不是同一个地址

你可能感兴趣的:(java,Android)