通过Intent,一个activity可以很容易的启动另一个activity,并且传递相关的数据给activity,通过Intent的putEXtra()方法,可以传递boolean、int、double等基本数据类型,如果想要传递对象的话,那么该对象必须实现Serializable接口,通过intent方法的putExtra(String name,Serializable value)方法,将对象传递过去。在接收方的activity通过intent.getExtra(name)方法获得该对象。
发送消息的acitivity的layout.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main" >
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="next" />
</RelativeLayout>
Main.java:
package com.app.main;
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 Main extends Activity {
Button btn = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) this.findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent();
Person p = new Person();
p.setName("wx");
p.setGender("boy");
p.setAge(25);
intent.putExtra("person", p);
intent.setClass(Main.this, NextMain.class);
Main.this.startActivity(intent);
}
});
}
}
接收方activity的layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textview1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
接收方activity:
package com.app.main;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class NextMain extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.nextmain);
TextView tv = (TextView) this.findViewById(R.id.textview1);
Intent intent = this.getIntent();
if (intent.getExtras().get("person") != null) {
Person p = (Person) intent.getExtras().get("person");
tv.setText("name:" + p.getName() + ",age:" + p.getAge()
+ ",gender:" + p.getGender());
}
}
}
效果如下: