Android Parcelable 序列化机制

废话少说,直接上代码

序列化对象类

package com.psj.myapplication.been;

import android.os.Parcel;
import android.os.Parcelable;

public class User implements Parcelable {

    private String name;
    private String sex;
    private int age;

    public User(String name, int age,String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    private User(Parcel in) {
        name = in.readString();
        age = in.readInt();
        sex = in.readString();
    }

    public static final Creator CREATOR = new Creator() {
        @Override
        public User createFromParcel(Parcel in) {
            return new User(in);
        }

        @Override
        public User[] newArray(int size) {
            return new User[size];
        }
    };


    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                '}';
    }

    //内容描述,一般不用不到
    @Override
    public int describeContents() {
        return 0;
    }

    //用于序列化
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        //将name 、 sex和age属性序列化出去
        dest.writeString(name);
        dest.writeInt(age);
        dest.writeString(sex);
    }

}

MainActivity

package com.psj.myapplication
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.psj.myapplication.been.User

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    fun click(view: View){

        val intent = Intent(this,SecondActivity::class.java);

        val user = User("Jie",18,"男");

        intent.putExtra("user",user);

        startActivity(intent);

    }


}

SecondActivity

package com.psj.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.psj.myapplication.been.User
import kotlinx.android.synthetic.main.activity_second.*

class SecondActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)

        intent?.let {

            it.getParcelableExtra("user")?.let { user ->

                tvInfo.text = user.toString()

            }

        }

    }
}

你可能感兴趣的:(Android Parcelable 序列化机制)