Android学习--Bundle(三)Parcelable编写练习

参考资料:https://www.jianshu.com/p/32a2ec8f35ae
https://www.cnblogs.com/tangZH/p/10998065.html

简单使用:

进行Android开发的时候,无法将对象的引用传给Activities或者Fragments,我们需要将这些对象放到一个Intent或者Bundle里面,然后再传递。

1. 建立两个Activity

https://jingyan.baidu.com/album/95c9d20da0165cec4e7561e0.html?picindex=9

1.在layout下,新建second_activity.xml




    

    


  1. 在AndroidManifest.xml里面新增activity
        
            
                

                
            
        

3.新建SecondActivity.java

public class SecondActivity extends AppCompatActivity {
    TextView view;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_activity);

    }

}
2.实现Parcelable接口

新建一个Book类,Author类同理

package com.example.paceltest;

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

public class Book implements Parcelable {

    private String name;
    private int id;
    //private String author;
    private Author author;

    public Book(String name, int id, Author author){
        this.name = name;
        this.id = id;
        this.author = author;
    }

    /**
     * 反序列化
     */
    protected Book(Parcel in) {
        name = in.readString();
        id = in.readInt();
        author = in.readParcelable(Author.class.getClassLoader());
    }

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

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

    @Override
    public int describeContents() {
        return 0;
    }

    /**
     *序列化
     */
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(id);
        dest.writeParcelable(author,0);
    }

    @Override
    public String toString(){
        return  "name : " + name + "\""+" id: "+id+"\""+" author: "+author.toString();
    }
}

在MainAcitivity中添加

    public void onClick(View view){
        //startActivity(new Intent("com.litreily.SecondActivity"));
        Intent intent = new Intent(MainActivity.this,SecondActivity.class);
        Author author = new Author("xxx","China");
        intent.putExtra("key",new Book("红宝书",1,author));
        startActivity(intent);
    }

在SecondActivity中添加

        view.setOnClickListener(new TextView.OnClickListener(){

            @Override
            public void onClick(View v) {
                Intent intent = getIntent();
                Book book = intent.getParcelableExtra("key");
                String out = book.toString();
                view.setText(out);
            }
        });

结果:


image.png

你可能感兴趣的:(Android学习--Bundle(三)Parcelable编写练习)