Intent 傳遞數據

1、Intent傳遞基本數據類型

傳遞

Intent intent=new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("key","value");

取出

String s=getIntent().getStringExtra("key");

還有一些其他的基本數據類型都可以以這樣的形式傳遞獲取,只需要在getStringExtra的地方將String換成對應數據類型就可以了,有幾個方法可以帶默認值,比如getIntent().getIntExtra(“number”,1);

2、Intent傳遞對象

而對象傳遞方式主要有以下兩種

(1)實現Serializable接口implements Serializable,這種思想是通過序列化的方式,序列化就是讓對象以流的形式存在,可以存儲在本地,也可以在網絡上傳輸。因爲對象不能直接傳輸,所以就使用這種可傳輸的形式。但是效率對比實現Parcelable要低一些,使用要簡單一些。

使用方式直接讓待傳遞的對象實現Serializable接口 ,在Activity中讀取的時候和基本數據類型的讀取一樣。

自己實現一個Person類

Intent intent=new Intent(MainActivity.this,Main2Activity.class);
Person person=new Person();
person.setName("hahha");
person.setId(123);
intent.putExtra("Serializable",person);
startActivity(intent);

獲取

Person person1=(Person)getIntent().getSerializableExtra("Serializable");
        System.out.println(person1.getName());

(2) 也可以實現Parcelable思想是將對象分解成可以直接傳輸的基本數據類型進行傳輸

對比Serializable要複雜一些

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

public class Person implements Parcelable {
    private String name;

    protected Person(Parcel in) {
        name = in.readString();//讀取
        id = in.readInt();
    }

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

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

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);//寫入
        dest.writeInt(id);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    private int id;

    public void setName() {

    }
}

因爲要實現接口裏的一些方法

首先是寫入 writeToParcel() dest.writexxx()方法一一寫入。 讀取,採用in.readxxx(),要注意的是讀取和寫入順序一定要一致。

describeContents() 一般返回0就行了

還有這個CREATOR ,創建了Parcelable.create的一種實現,重寫 方法createFromParcel( newArray()只需要返回數組大小,要有泛型。

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

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

傳遞時候和Serializable使用一樣,獲取的時候

Person person1=(Person)getIntent().getParcelableExtra("Parcelable");
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章