Android 通過 Intent 傳遞類對象,androidintent

來源:互聯網
上載者:User

Android 通過 Intent 傳遞類對象,androidintent

(轉:http://www.cnblogs.com/shaocm/archive/2013/01/08/2851248.html)

Android中Intent傳遞類對象提供了兩種方式一種是 通過實現Serializable介面傳遞對象,一種是通過實現Parcelable介面傳遞對象。

要求被傳遞的對象必須實現上述2種介面中的一種才能通過Intent直接傳遞。

Intent中傳遞這2種對象的方法:

1 Bundle.putSerializable(Key,Object);  //實現Serializable介面的對象2 3 Bundle.putParcelable(Key, Object); //實現Parcelable介面的對象

以下以最常用的Serializable方式為例 :

假設由登入介面(Login)跳轉到主介面(MainActivity)傳遞的對象為登入的使用者資訊 User類

首先建立一個序列化類別:User

 1 import java.io.Serializable; 2  3 public class User implements Serializable { 4    private int ID; 5     private String UserName;     6     private String PWD;     7     public final void setID(int value) 8     { 9         ID = value;10     }11     public final int getID()12     {13         return ID;14     }    15     public final void setUserName(String value)16     {17         UserName = value;18     }19     public final String getUserName()20     {21         return UserName;22     }  23     public final void setPWD(String value)24     {25         PWD = value;26     }27 28     public final String getPWD()29     {30         return PWD;31     }    32     33 }

登入表單登入後傳遞內容

1 Intent intent = new Intent();2 intent.setClass(Login.this, MainActivity.class);3 Bundle bundle = new Bundle();4 bundle.putSerializable("user", user);5 intent.putExtras(bundle);6 this.startActivity(intent);

接收端

1 Intent intent = this.getIntent(); 2 user=(User)intent.getSerializableExtra("user");

以上就可以實現對象的傳遞。

補充:

如果傳遞的是List<Object>,可以把list強轉成Serializable類型,而且object類型也必須實現了Serializable介面

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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.