<?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:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button android:id="@+id/btn_01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Serilizable"/>
<Button android:id="@+id/btn_02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Parcelable"/>
</LinearLayout>
MianActivity.java
package cn.edu.wtu;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class IntentDemo extends Activity implements OnClickListener{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn_01 = (Button) findViewById(R.id.btn_01);
Button btn_02 = (Button) findViewById(R.id.btn_02);
btn_01.setOnClickListener(this);
btn_02.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.btn_01:{
Intent intent = new Intent(this,PersonView.class);
Person mPerson = new Person();
mPerson.setAge(20);
mPerson.setName("moon");
Bundle bundle = new Bundle();
bundle.putSerializable("person", mPerson);
intent.putExtras(bundle);
startActivity(intent);
break;
}
case R.id.btn_02:{
Intent intent = new Intent(this,BookView.class);
Book book = new Book();
book.setName("manmonth");
book.setTime("1975");
book.setAuthor("Brooks");
Bundle bundle = new Bundle();
bundle.putParcelable("book", book);
intent.putExtras(bundle);
startActivity(intent);
break;
}
}
}
}
取值
public class PersonView extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
TextView text = new TextView(this);
Person person = (Person)getIntent().getSerializableExtra("person");
text.setText("name:"+person.getName()+"/nage:"+person.getAge()+"/n");
setContentView(text);
}
}
取值
public class BookView extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
TextView text = new TextView(this);
Book book = (Book) getIntent().getParcelableExtra("book");
text.setText("name:"+book.getName()+"/nautor:"+book.getAuthor()+"/ntime:"+book.getTime());
setContentView(text);
}
}