欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android 不同Activity間數(shù)據(jù)的傳遞 Bundle對象的應(yīng)用

 更新時(shí)間:2013年04月19日 17:21:34   作者:  
本篇文章小編為大家介紹,Android 不同Activity間數(shù)據(jù)的傳遞 Bundle對象的應(yīng)用。需要的朋友參考下

在應(yīng)用中,可能會(huì)在當(dāng)跳轉(zhuǎn)到另外一個(gè)Activity的時(shí)候需要傳遞數(shù)據(jù)過去,這時(shí)就可能用Bundle對象;

在MainActivity中,有一個(gè)導(dǎo)航至BActivity的Intent,

Intent

復(fù)制代碼 代碼如下:

{

  Intent intent = new Intent(Context context, Class<?> class);
  //new一個(gè)Bundle對象,并將要傳遞的數(shù)據(jù)導(dǎo)入,Bunde相當(dāng)于Map<Key,Value>結(jié)構(gòu)   
  Bundle bundle = new Bundle();
  bundle.putString("name","Livingstone");
  bundle.putXXX(XXXKey, XXXValue);
  //將Bundle對象添加給Intent
  intent.putExtras(bundle);
  //調(diào)用intent對應(yīng)的Activity
  startActivity(intent);

}


在BActivity中,通過以下代碼獲取MainActivity所傳過來的數(shù)據(jù)

  Bundle bundle = this.getIntent().getExtras();// 獲取傳遞過來的封裝了數(shù)據(jù)的Bundle
  String name = bundle.getString("name");// 獲取name_Key對應(yīng)的Value
  // 獲取值時(shí),添加進(jìn)去的是什么類型的獲取什么類型的值

     --> bundle.getXXX(XXXKey);

       return XXXValue

上面講述的都是一般的基本數(shù)據(jù)類型,當(dāng)需要傳遞對象的時(shí)候,可以使該對象實(shí)現(xiàn)Parcelable或者是Serializable接口;

通過Bundle.putParcelable(Key,Obj)及Bundle.putSerializable(Key,Obj)方法將對象添加到Bundle中,再將此Bundle對象添加到Intent中!


在跳轉(zhuǎn)的目標(biāo)頁面通過Intent.getParcelableExtra(Key)獲取實(shí)現(xiàn)了Parcelable的對象;

在跳轉(zhuǎn)的目標(biāo)頁面通過Intent.getSerializableExtra(Key)獲取實(shí)現(xiàn)了Serializable的對象;

今天在研究的時(shí)候發(fā)現(xiàn),Intent.putExtra(Key,Value);其實(shí)也可以傳遞數(shù)據(jù),包括上面所講的對象!

實(shí)現(xiàn)Serializable接口很簡單,不再描述;

下面描述實(shí)現(xiàn)Parcelable接口:

復(fù)制代碼 代碼如下:

public class Book implements Parcelable {
 private String bookName;
 private String author;

 public static final Parcelable.Creator CREATOR = new Creator() {// 此處必須定義一個(gè)CREATOR成員變量,要不然會(huì)報(bào)錯(cuò)!

  @Override
  public Book createFromParcel(Parcel source) {// 從Parcel中獲取數(shù)據(jù),在獲取數(shù)據(jù)的時(shí)候需要通過此方法獲取對象實(shí)例
   Book book = new Book();
   book.setAuthor(source.readString());// 從Parcel讀取數(shù)據(jù),讀取數(shù)據(jù)與寫入數(shù)據(jù)的順序一致!
   book.setBookName(source.readString());
   return book;
  }

  @Override
  public Book[] newArray(int size) {
   return new Book[size];
  }
 };

 @Override
 public int describeContents() {
  return 0;
 }

 @Override// 寫入Parcel
 public void writeToParcel(Parcel dest, int flags) {
  dest.writeString(author);// 將數(shù)據(jù)寫入Parcel,寫入數(shù)據(jù)與讀取數(shù)據(jù)的順序一樣!
  dest.writeString(bookName);
 }
}


 關(guān)于Parcel,大概查閱了一下描述:

 一個(gè)final類,用于寫或讀各種數(shù)據(jù),所有的方法不過就是writeValue(Object)和read(ClassLoader)!(個(gè)人翻譯理解)

相關(guān)文章

最新評(píng)論