Android 中Parcelable的作用

來源:互聯網
上載者:User

android提供了一種新的類型:Parcel。本類被用作封裝資料的容器,封裝後的資料可以通過Intent或IPC傳遞。 除了基本類型以

外,只有實現了Parcelable介面的類才能被放入Parcel中。

 

Parcelable實現要點:需要實現三個東西

1)writeToParcel 方法。該方法將類的資料寫入外部提供的Parcel中.聲明如下:

writeToParcel (Parcel dest, int flags) 具體參數含義見javadoc

2)describeContents方法。沒搞懂有什麼用,反正直接返回0也可以

3)靜態Parcelable.Creator介面,本介面有兩個方法:

createFromParcel(Parcel in) 實現從in中建立出類的執行個體的功能

newArray(int size) 建立一個類型為T,長度為size的數組,僅一句話(return new T[size])即可。估計本方法是供外部類還原序列化本類數組使用。

測試用的接收資訊Activity

import android.app.Activity;   

import android.content.Intent;

import android.os.Bundle;
import android.os.Parcelable;

public class Test extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent i = getIntent();
Person p = i.getParcelableExtra("yes");
System.out.println("---->"+p.name);
System.out.println("---->"+p.map.size());
}
}

發送的Activity

import java.util.HashMap;   

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class TestNew extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent();
Person p = new Person();
p.map = new HashMap<String,String>();
p.map.put("yes", "ido");
p.name="ok";
intent.putExtra("yes", p);
intent.setClass(this, Test.class);
startActivity(intent);
}
}

Parcelable的實作類別

import java.util.HashMap;   

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

public class Person implements Parcelable {

public HashMap<String,String> map = new HashMap<String,String> ();

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

@Override
public void writeToParcel(Parcel dest, int flags) {

dest.writeMap(map);
dest.writeString(name);
}
public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
//重寫Creator

@Override
public Person createFromParcel(Parcel source) {
Person p = new Person();
p.map=source.readHashMap(HashMap.class.getClassLoader());
p.name=source.readString();
return p;
}

@Override
public Person[] newArray(int size) {
// TODO Auto-generated method stub
return null;
}
};

}

 

下面寫一下轉載自http://blog.csdn.net/zyc13701469860/article/details/6429934的對Parcel的解說:

在SDK中 Parcelable類的概述是這樣的:Interface for classes whose instances can be written to and restored from a Parcel. Classes implementing the Parcelable interface must also have a static field called CREATOR, which is an object implementing theParcelable.Creator interface.

 

這個介面的執行個體是通過Parcel進行儲存的,在使用Parcelable的時候必須使用Parcelable.Creator。

 

下面上代碼:

首先修改main.xml,增加一個button

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Parcelable">
</Button>
</LinearLayout>

然後是主Activity ParcelableTest.java,這個類顯示UI,並通過button點擊事件啟動另一個Activity -- ParcelableTest2,同時通過Parcelable介面傳遞一些資料。

package parcelable_test.com;  

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ParcelableTest extends Activity implements OnClickListener{
public static final String KEY = "key";
private Button button;
public static final String TAG = "Parcelable";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
Log.d(TAG, "ParcelableTest");
}

private void init(){
button = (Button)findViewById(R.id.button);
button.setOnClickListener(this);
}

private void fun(){
Log.d(TAG, "fun");
Person mPerson = new Person();
mPerson.setName("tom");
mPerson.setAge(25);
Intent mIntent = new Intent(this,parcelable_test.com.ParcelableTest2.class);
Bundle mBundle = new Bundle();
mBundle.putParcelable(KEY, mPerson);
mIntent.putExtras(mBundle);
startActivity(mIntent);
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
fun();
break;

default:
break;
}
}
}

ParcelableTest2.java,這個類用於擷取ParcelableTest傳出的資料,並顯示在UI上。

package parcelable_test.com;  

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class ParcelableTest2 extends Activity{
private static final String TAG = ParcelableTest.TAG;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d(TAG, "ParcelableTest2");
TextView textView = new TextView(this);
Person mPerson = (Person)getIntent().getParcelableExtra(ParcelableTest.KEY);
textView.setText("name = " + mPerson.getName() + " age = " + mPerson.getAge());
setContentView(textView);
}
}

下面就是最重要的類Person,Person類引用了Parcelable介面

package parcelable_test.com;  
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
public class Person implements Parcelable{
private String name;
private int age;
private static final String TAG = ParcelableTest.TAG;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static final Parcelable.Creator<Person> CREATOR = new Creator<Person>() {
@Override
public Person createFromParcel(Parcel source) {
Log.d(TAG,"createFromParcel");
Person mPerson = new Person();
mPerson.name = source.readString();
mPerson.age = source.readInt();
return mPerson;
}
@Override
public Person[] newArray(int size) {
// TODO Auto-generated method stub
return new Person[size];
}
};
@Override
public int describeContents() {
// TODO Auto-generated method stub
Log.d(TAG,"describeContents");
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
Log.d(TAG,"writeToParcel");
dest.writeString(name);
dest.writeInt(age);
}
}

通過log可知程式的運行情況,在mBundle.putParcelable(KEY, mPerson);時,調用了Person類中的public void writeToParcel(Parcel dest, int flags)方法,並向dest寫資料,在 Person mPerson = (Person)getIntent().getParcelableExtra(ParcelableTest.KEY);的時候,調用了Person類中的public Person createFromParcel(Parcel source) 方法,建立了一個Person對象,並給這個對象的屬性賦值,這裡的Parcel source和Parcel dest,是相同的,然後返回這個Person對象。最後就可以列印出mPerson的屬性資訊了。

Parcel可以用來存放很多資料,比如都是String和int,又或者有一個String和HashMap<String,String>的集合,都很方便。

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.