使用Serializable方式
前提:Object需要实现Serializable接口
Serializable方式传递Object的语法:bundle.putSerializable(key,object);
用Serializable方式接收Object的语法:object=(Object) getIntent().getSerializableExtra(key);
实现Serializable接口就是把对象序列化,然后再传输,和Java的常用编程没什么明显区别,而且Object不需要明显改变,推荐用这种方式,具体步骤如下:
1)首先创建一个PersonInfo实体类实现Serializable接口,然后定义name、address、age属性,再生成相应的get、set方法,具体代码如下:
package zjh.android.bean;
import java.io.Serializable;
@SuppressWarnings("serial")
public class PersonInfo implements Serializable{
private String name;
private String address;
private int age;
public PersonInfo() {
}
public PersonInfo(String name,String address,int age){
this.name = name;
this.address = address;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
|
2)创建一个用来发送Serializable数据类型的SendActivity类,具体实现代码如下:
package zjh.android.lx;
import zjh.android.bean.PersonInfo;
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 SendActivity extends Activity {
private PersonInfo personInfo;
private Button send;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_send);
this.send = (Button)super.findViewById(R.id.send);
this.send.setOnClickListener(new OnClickListenerImpl());
}
private final class OnClickListenerImpl implements OnClickListener{
@Override
public void onClick(View v) {
personInfo = new PersonInfo("张三", "广州", 22);
Intent intent = new Intent(SendActivity.this,ReceiveActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("personInfo", personInfo);
intent.putExtras(bundle);
SendActivity.this.startActivity(intent);
}
}
}
|
3)创建一个用来接收Serializable数据类型的ReceiveActivity类,代码如下:
package zjh.android.lx;
import zjh.android.bean.PersonInfo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class ReceiveActivity extends Activity {
private TextView show;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.receive);
this.show = (TextView) super.findViewById(R.id.show);
Intent intent = super.getIntent();
PersonInfo personInfo = (PersonInfo) intent
.getSerializableExtra("personInfo");
this.show
.setText("name=" + personInfo.getName() + "\n" + "address="
+ personInfo.getAddress() + "\n" + "age="
+ personInfo.getAge());
}
}
|
4)在AndroidMainfest.xml文件中添加一个相应的activity,具体如下:
<activity android:name="zjh.android.lx.ReceiveActivity"/> |
此时,通过Intent传递Serializable数据类型的数据就实现了。