在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);
}
}