Android中Intent中如何传递对象,就我目前所知道的有两种方法,一种是Bundle.putSerializable(Key,Object);另一种是Bundle.putParcelable(Key, Object);
本文只介绍好用的Serializable方法,想知道更多请自行百度。
第一步:新建一个类一个是Person.java实现Serializable接口
Person.java:
- package com.tutor.objecttran;
- import java.io.Serializable;
- public class Person implements Serializable {
- private static final long serialVersionUID = -7060210544600464481L;
- private String name;
- private int age;
- 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;
- }
- }
第二步:发送对象
ObjectTranDemo.java:
- package com.tutor.objecttran;
- 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 ObjectTranDemo extends Activity implements OnClickListener {
- private Button sButton,pButton;
- public final static String SER_KEY = "anystring";
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- setupViews();
- }
- //我的一贯作风呵呵
- public void setupViews(){
- sButton = (Button)findViewById(R.id.button1);
- sButton.setOnClickListener(this);
- }
- //Serializeable传递对象的方法
- public void SerializeMethod(){
- Person mPerson = new Person();
- mPerson.setName("H3c");
- mPerson.setAge(23);
- Intent mIntent = new Intent(this,ObjectTranDemo1.class);
- Bundle mBundle = new Bundle();
- mBundle.putSerializable(SER_KEY,mPerson);
- mIntent.putExtras(mBundle);
- startActivity(mIntent);
- }
- //铵钮点击事件响应
- public void onClick(View v) {
- SerializeMethod();
- }
- }
第三步:接收对象
ObjectTranDemo1.java:
- package com.tutor.objecttran;
- import android.app.Activity;
- import android.os.Bundle;
- import android.widget.TextView;
- public class ObjectTranDemo1 extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- TextView mTextView = new TextView(this);
- Person mPerson = (Person)getIntent().getSerializableExtra(ObjectTranDemo.SER_KEY);
- mTextView.setText("You name is: " + mPerson.getName() + "/n"+
- "You age is: " + mPerson.getAge());
- setContentView(mTextView);
- }
- }
==================================================THE END=================================================