Android Bundle詳解

1.Bundle簡介:

Bundle主要用於傳輸數據,它保存的數據,是以key-value的形式存儲的。
Bundle常用於在Activity間傳遞數據 ,當不bundle傳遞的是對象或對象數組時,必須實現Serializable或Parcelable接口,下面分別介紹bundle在activity間如何傳遞基本數據類型和對象。

2.傳遞基本類型

Bundle提供了各種putXxx()/getXxx()方法,用於讀寫基本數據類型,Bundle用於讀寫基本數據類型的API有:
Android Bundle詳解

示例
寫數據的方法:

                Bundle bundle=new Bundle();
                bundle.putString("name","police");
                bundle.putInt("years",8);
                final Intent intent=new Intent().setClassName("police.myapp","police.myapp.Main2Activity");
                intent.putExtras(bundle);
                startActivity(intent);

執行後將bundle綁定到intent,傳遞到Mian2Activity

讀數據的方法:
(Intent.getExtras()獲取bundle對象)

      Bundle bundle=this.getIntent().getExtras();
        String bundleString=bundle.getString("name");
        int bundleInt=bundle.getInt("years");
        textView.setText(bundleString+bundleInt);

3.傳遞Parcelable類型的對象

3.1Parcelable說明

Parcelable是Android自定義的一個接口,它包括將數據寫入Parcel和從Parcel中讀出的API。
一個實體(用類來表示),如果需要封裝到Bundle中去,可以通過實現Parcelable接口來完成。

4.傳遞Serializable類型的對象

請看原文

轉自:https://blog.csdn.net/suncherrydream/article/details/52974500

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章