通过 Intent 传递类对象

来源:互联网 发布:应用统计学专业知乎 编辑:程序博客网 时间:2024/05/01 17:12
Android中Intent传递类对象提供了两种方式一种是 通过实现Serializable接口传递对象一种是通过实现Parcelable接口传递对象

要求被传递的对象必须实现上述2种接口中的一种才能通过Intent直接传递

Intent中传递这2种对象的方法:

Bundle.putSerializable(Key,Object);  //实现Serializable接口的对象Bundle.putParcelable(Key, Object); //实现Parcelable接口的对象
Person.java

package com.hust.bundletest;import java.io.Serializable;public class Person implements Serializable {    String name;    String password;    String sex;public Person(String name, String password, String sex) {super();this.name = name;this.password = password;this.sex = sex;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}    }
注册窗体发送Intent的代码:

    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Button btn=(Button) findViewById(R.id.button1);                  btn.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v) {// TODO Auto-generated method stub//获得的三个组件EditText name=(EditText) findViewById(R.id.name);        EditText password=(EditText) findViewById(R.id.password);        RadioButton male=(RadioButton) findViewById(R.id.radio0);        //判断是否被选        String sex=(male.isChecked())?"男":"女";        //封装成一个对象        Person p=new Person(name.getText().toString(),password.getText().toString(),sex);//创建Bundle对象Bundle bundle=new Bundle();bundle.putSerializable("person", p);//Bundle中放一个对象//创建一个Intent对象Intent intent=new Intent(MainActivity.this,ResultActivity.class);intent.putExtras(bundle);//启动intent对应的ActivitystartActivity(intent);}                });
接收端的代码:

@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_result);//获取显示组件TextView name=(TextView) findViewById(R.id.text1);TextView password=(TextView) findViewById(R.id.text2);TextView sex=(TextView) findViewById(R.id.text3);//获取Intent对象Intent intent=getIntent();//从Intent对象中获取序列数据//Person p=(Person) intent.getSerializableExtra("person");相当于Bundle bundle=intent.getExtras();//获取Bundle对象Person p=(Person) bundle.getSerializable("person");//Bundle对象中获取可序列化对象name.setText(p.getName());password.setText(p.getPassword());sex.setText(p.getSex());}
以上就可以实现对象的传递。
如果传递的是List<Object>,可以把list强转成Serializable类型,而且object类型也必须实现了Serializable接口

Intent.putExtras(key, (Serializable)list) 
(List<YourObject>)getIntent().getSerializable(key)

1 0
原创粉丝点击