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");