Android中Intent传递类对象提供了两种方式一种是 经过实现Serializable接口传递对象,一种是经过实现Parcelable接口传递对象。java
要求被传递的对象必须实现上述2种接口中的一种才能经过Intent直接传递。this
Intent中传递这2种对象的方法:spa
Bundle.putSerializable(Key,Object); //实现Serializable接口的对象 Bundle.putParcelable(Key, Object); //实现Parcelable接口的对象
如下以最经常使用的Serializable方式为例 :code
假设由登陆界面(Login)跳转到主界面(MainActivity)传递的对象为登陆的用户信息 User类对象
首先建立一个序列化类:Userblog
import java.io.Serializable; public class User implements Serializable { private int ID; private String UserName; private String PWD; public final void setID(int value) { ID = value; } public final int getID() { return ID; } public final void setUserName(String value) { UserName = value; } public final String getUserName() { return UserName; } public final void setPWD(String value) { PWD = value; } public final String getPWD() { return PWD; } }
登陆窗体登陆后传递内容接口
Intent intent = new Intent(); intent.setClass(Login.this, MainActivity.class); Bundle bundle = new Bundle(); bundle.putSerializable("user", user); intent.putExtras(bundle); this.startActivity(intent);
接收端get
Intent intent = this.getIntent(); user=(User)intent.getSerializableExtra("user");
以上就能够实现对象的传递。it
补充:io
若是传递的是List<Object>,能够把list强转成Serializable类型,并且object类型也必须实现了Serializable接口
Intent.putExtras(key, (Serializable)list)
接收
(List<YourObject>)getIntent().getSerializable(key)
另外一种简单的
Intent intent = new Intent(); intent.setClass(Login.this, MainActivity.class); Bundle bundle = new Bundle(); bundle.putSerializable("user",(
Serializable
) user); intent.putExtras(bundle); this.startActivity(intent);
Fragment传递数据
FragmentTransaction fragmentTransaction = getChildFragmentManager()
.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, goodsType);
//经过bundle传值给MyFragment
Bundle bundle = new Bundle();
bundle.putSerializable("goodstype", twotype);
goodsType.setArguments(bundle);
fragmentTransaction.commit();
接收
list= (ArrayList) getArguments().getSerializable("goodstype");