android中的bundle使用


         <!--一個博主專欄付費入口結束-->
        <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-4a3473df85.css">
                                    <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-4a3473df85.css">
            <div class="htmledit_views" id="content_views">


1 Bundle介紹

Bundle主要用於傳遞數據;它保存的數據,是以key-value(鍵值對)的形式存在的。

 

我們經常使用Bundle在Activity之間傳遞數據,傳遞的數據可以是boolean、byte、int、long、float、double、string等基本類型或它們對應的數組,也可以是對象或對象數組。當Bundle傳遞的是對象或對象數組時,必須實現Serializable 或Parcelable接口。下面分別介紹Activity之間如何傳遞基本類型、傳遞對象。

 

2傳遞基本類型

Bundle提供了各種常用類型的putXxx()/getXxx()方法,用於讀寫基本類型的數據。Bundle操作基本數據類型的API表格如下所示:

 

寫數據的方法如下:


   
   
  
  
          
  1. // "com.test" is the package name of the destination class
  2. // "com.test.Activity02" is the full class path of the destination class
  3. Intent intent = new Intent().setClassName( "com.bundletest", "com.bundletest.Bundle02");
  4. Bundle bundle = new Bundle();
  5. bundle.putString( "name", "skywang");
  6. bundle.putInt( "height", 175);
  7. intent.putExtras(bundle);
  8. startActivity(intent);
  9. // end current class
  10. finish();


對應的讀數據的方法如下:


   
   
  
  
          
  1. Bundle bundle = this.getIntent().getExtras();
  2. String name = bundle.getString( "name");
  3. int height = bundle.getInt( "height");


3傳遞Parcelable類型的對象

3.1 Parcelable說明

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


Parcelable和Serializable的API如下表:



3.2 Parcelable接口說明


   
   
  
  
          
  1. public interface Parcelable {
  2. //內容描述接口,基本不用管
  3. public int describeContents();
  4. //寫入接口函數,打包
  5. public void writeToParcel(Parcel dest, int flags);
  6. //讀取接口,目的是要從Parcel中構造一個實現了Parcelable的類的實例處理。因為實現類在這里還是不可知的,所以需要用到模板的方式,繼承類名通過模板參數傳入。
  7. //為了能夠實現模板參數的傳入,這里定義Creator嵌入接口,內含兩個接口函數分別返回單個和多個繼承類實例。
  8. public interface Creator<T> {
  9. public T createFromParcel(Parcel source);
  10. public T[] newArray( int size);
  11. }
  12. }


3.3 Parcelable接口的實現方法

從parcelable接口定義中,我們可以看到,實現parcelable接口,需要我們實現下面幾個方法:
(01)describeContents方法。內容接口描述,默認返回0就可以;
(02)writeToParcel 方法。該方法將類的數據寫入外部提供的Parcel中.即打包需要傳遞的數據到Parcel容器保存,以便從parcel容器獲取數據,該方法聲明如下:
writeToParcel(Parcel dest, int flags) 具體參數含義見doc文檔
(3.)靜態的Parcelable.Creator接口,本接口有兩個方法:
createFromParcel(Parcelin)  從Parcel容器中讀取傳遞數據值,封裝成Parcelable對象返回邏輯層。
newArray(int size) 創建一個類型為T,長度為size的數組,僅一句話(returnnew T[size])即可。方法是供外部類反序列化本類數組使用。

 

4傳遞Serializable類型的對象

4.1 Serializable說明

Serializable是一個對象序列化的接口。一個類只有實現了Serializable接口,它的對象才是可序列化的。因此如果要序列化某些類的對象,這些類就必須實現Serializable接口。而實際上,Serializable是一個空接口,沒有什么具體內容,它的目的只是簡單的標識一個類的對象可以被序列化。

4.2 Serializable接口的實現方法

很簡單,只要implements Serializable接口就可以了

 

5 demo演示程序

下面是對實現上述三種數據傳遞方式的BundleTest(demo程序)進行簡要介紹

5.1 demo概要

BundleTest共包含了4個java文件和2個layout文件(main.xml和main2.xml)

Bundle01.java     —— 默認的主Activity窗口。

Bundle02.java     —— 主Activity用於跳轉的目的窗口。

Book.java            —— 實現Parcelable接口的類

Person.java        —— 實現Serializable接口的類

main.xml             —— Bundle01.java的layout文件

main2.xml           —— Bundle02.java的layout文件

 

工程文件結構如下所示:


 

5.2代碼

AndroidManifest.xml


   
   
  
  
          
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package= "com.bundletest"
  4. android:versionCode= "1"
  5. android:versionName= "1.0">
  6. <application android:icon="@drawable/icon" android:label="@string/app_name">
  7. <activity android:name=".Bundle01"
  8. android:label= "@string/app_name">
  9. <intent-filter>
  10. <action android:name="android.intent.action.MAIN" />
  11. <category android:name="android.intent.category.LAUNCHER" />
  12. </intent-filter>
  13. </activity>
  14. <activity android:name=".Bundle02"> </activity>
  15. </application>
  16. <uses-sdk android:minSdkVersion="11" />
  17. </manifest>



main.xml


   
   
  
  
          
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation= "vertical"
  4. android:layout_width= "fill_parent"
  5. android:layout_height= "fill_parent"
  6. >
  7. <TextView
  8. android:layout_width= "fill_parent"
  9. android:layout_height= "wrap_content"
  10. android:text= "@string/app_01"
  11. />
  12. <Button
  13. android:id= "@+id/btnBasic"
  14. android:layout_width= "fill_parent"
  15. android:layout_height= "wrap_content"
  16. android:text= "@string/text_basic"
  17. />
  18. <Button
  19. android:id= "@+id/btnPar"
  20. android:layout_width= "fill_parent"
  21. android:layout_height= "wrap_content"
  22. android:text= "@string/text_par"
  23. />
  24. <Button
  25. android:id= "@+id/btnSer"
  26. android:layout_width= "fill_parent"
  27. android:layout_height= "wrap_content"
  28. android:text= "@string/text_ser"
  29. />
  30. </LinearLayout>



main2.xml


   
   
  
  
          
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation= "vertical"
  4. android:layout_width= "fill_parent"
  5. android:layout_height= "fill_parent"
  6. >
  7. <TextView
  8. android:layout_width= "fill_parent"
  9. android:layout_height= "wrap_content"
  10. android:text= "@string/app_02"
  11. />
  12. <Button
  13. android:id= "@+id/btnBack"
  14. android:layout_width= "fill_parent"
  15. android:layout_height= "wrap_content"
  16. android:text= "@string/text_jump_back"
  17. />
  18. </LinearLayout>



strings.xml


   
   
  
  
          
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. <string name="hello">Hello MyBundleTest! </string>
  4. <string name="app_name">MyBundleTest </string>
  5. <string name="app_01">Bundle_01 </string>
  6. <string name="app_02">Bundle_02 </string>
  7. <string name="text_basic">Bundle Basic Data </string>
  8. <string name="text_par">Bundle Parcelable Data </string>
  9. <string name="text_ser">Bundle Seriable Data </string>
  10. <string name="text_jump_back">Jump Back to Bundler01 </string>
  11. </resources>



Bundle01.java


   
   
  
  
          
  1. package com.bundletest;
  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. import android.view.View;
  5. import android.view.View.OnClickListener;
  6. import android.widget.Button;
  7. import android.content.Intent;
  8. import android.util.Log;
  9. public class Bundle01 extends Activity implements View.OnClickListener{
  10. private static final String TAG = "skywang-->Bundle01";
  11. private Button mBtnBasic = null;
  12. private Button mBtnPar = null;
  13. private Button mBtnSer = null;
  14. @Override
  15. public void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. setContentView(R.layout.main);
  18. mBtnBasic = (Button) findViewById(R.id.btnBasic);
  19. mBtnBasic.setOnClickListener( this);
  20. mBtnPar = (Button) findViewById(R.id.btnPar);
  21. mBtnPar.setOnClickListener( this);
  22. mBtnSer = (Button) findViewById(R.id.btnSer);
  23. mBtnSer.setOnClickListener( this);
  24. }
  25. @Override
  26. public void onClick(View view) {
  27. switch (view.getId()) {
  28. case R.id.btnBasic:
  29. sendBasicDataThroughBundle();
  30. break;
  31. case R.id.btnPar:
  32. sendParcelableDataThroughBundle();
  33. break;
  34. case R.id.btnSer:
  35. sendSeriableDataThroughBundle();
  36. break;
  37. default:
  38. break;
  39. }
  40. }
  41. // sent basic data, such as int, strin, etc... through bundle
  42. private void sendBasicDataThroughBundle(){
  43. // "com.test" is the package name of the destination class
  44. // "com.test.Activity02" is the full class path of the destination class
  45. Intent intent = new Intent().setClassName( "com.bundletest", "com.bundletest.Bundle02");
  46. Bundle bundle = new Bundle();
  47. bundle.putString( "name", "skywang");
  48. bundle.putInt( "height", 175);
  49. intent.putExtras(bundle);
  50. startActivity(intent);
  51. // end current class
  52. finish();
  53. }
  54. // sent object through Pacelable
  55. private void sendParcelableDataThroughBundle(){
  56. Intent intent = new Intent().setClassName( "com.bundletest", "com.bundletest.Bundle02");
  57. Book mBook = new Book();
  58. mBook.setBookName( "Android");
  59. mBook.setAuthor( "skywang");
  60. mBook.setPublishTime( 2013);
  61. Bundle mBundle = new Bundle();
  62. mBundle.putParcelable( "ParcelableValue", mBook);
  63. intent.putExtras(mBundle);
  64. startActivity(intent);
  65. finish();
  66. }
  67. // sent object through seriable
  68. private void sendSeriableDataThroughBundle(){
  69. Intent intent = new Intent().setClassName( "com.bundletest", "com.bundletest.Bundle02");
  70. Person mPerson = new Person();
  71. mPerson.setName( "skywang");
  72. mPerson.setAge( 24);
  73. Bundle mBundle = new Bundle();
  74. mBundle.putSerializable( "SeriableValue",mPerson);
  75. intent.putExtras(mBundle);
  76. startActivity(intent);
  77. finish();
  78. }
  79. }



Bundle02.java


   
   
  
  
          
  1. package com.bundletest;
  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. import android.view.View;
  5. import android.view.View.OnClickListener;
  6. import android.widget.Button;
  7. import android.content.Intent;
  8. import android.util.Log;
  9. public class Bundle02 extends Activity implements View.OnClickListener {
  10. private static final String TAG = "skywang-->Bundle02";
  11. private Button mBtnBack = null;
  12. @Override
  13. public void onCreate(Bundle savedInstanceState) {
  14. super.onCreate(savedInstanceState);
  15. setContentView(R.layout.main2);
  16. mBtnBack = (Button) findViewById(R.id.btnBack);
  17. mBtnBack.setOnClickListener( this);
  18. receiveBasicData();
  19. receiveParcelableData();
  20. receiveSeriableData();
  21. }
  22. private void receiveBasicData() {
  23. Bundle bundle = this.getIntent().getExtras();
  24. String name = bundle.getString( "name");
  25. int height = bundle.getInt( "height");
  26. if (name != null && height != 0)
  27. Log.d(TAG, "receice basic data -- " +
  28. "name="+name+ ", height="+height);
  29. }
  30. private void receiveParcelableData() {
  31. Book mBook = (Book)getIntent().getParcelableExtra( "ParcelableValue");
  32. if (mBook != null)
  33. Log.d(TAG, "receice parcel data -- " +
  34. "Book name is: " + mBook.getBookName()+ ", "+
  35. "Author is: " + mBook.getAuthor() + ", "+
  36. "PublishTime is: " + mBook.getPublishTime());
  37. }
  38. private void receiveSeriableData() {
  39. Person mPerson = (Person)getIntent().getSerializableExtra( "SeriableValue");
  40. if (mPerson != null)
  41. Log.d(TAG, "receice serial data -- " +
  42. "The name is:" + mPerson.getName() + ", "+
  43. "age is:" + mPerson.getAge());
  44. }
  45. @Override
  46. public void onClick(View view) {
  47. switch (view.getId()) {
  48. case R.id.btnBack:
  49. {
  50. // "com.test" is the package name of the destination class
  51. // "com.test.Activity01" is the full class path of the destination class
  52. Intent intent = new Intent().setClassName( "com.bundletest", "com.bundletest.Bundle01");
  53. startActivity(intent);
  54. // end current class
  55. finish();
  56. }
  57. break;
  58. default:
  59. break;
  60. }
  61. }
  62. }



Book.java


   
   
  
  
          
  1. package com.bundletest;
  2. import android.os.Parcel;
  3. import android.os.Parcelable;
  4. public class Book implements Parcelable {
  5. private String bookName;
  6. private String author;
  7. private int publishTime;
  8. public String getBookName() {
  9. return bookName;
  10. }
  11. public void setBookName(String bookName) {
  12. this.bookName = bookName;
  13. }
  14. public String getAuthor() {
  15. return author;
  16. }
  17. public void setAuthor(String author) {
  18. this.author = author;
  19. }
  20. public int getPublishTime() {
  21. return publishTime;
  22. }
  23. public void setPublishTime(int publishTime) {
  24. this.publishTime = publishTime;
  25. }
  26. public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() {
  27. @Override
  28. public Book createFromParcel(Parcel source) {
  29. Book mBook = new Book();
  30. mBook.bookName = source.readString();
  31. mBook.author = source.readString();
  32. mBook.publishTime = source.readInt();
  33. return mBook;
  34. }
  35. @Override
  36. public Book[] newArray( int size) {
  37. return new Book[size];
  38. }
  39. };
  40. @Override
  41. public int describeContents() {
  42. return 0;
  43. }
  44. @Override
  45. public void writeToParcel(Parcel parcel, int flags) {
  46. parcel.writeString(bookName);
  47. parcel.writeString(author);
  48. parcel.writeInt(publishTime);
  49. }
  50. }



Person.java


   
   
  
  
          
  1. package com.bundletest;
  2. import java.io.Serializable;
  3. public class Person implements Serializable {
  4. private static final long serialVersionUID = 1L;
  5. private String name;
  6. private int age;
  7. public String getName() {
  8. return name;
  9. }
  10. public void setName(String name) {
  11. this.name = name;
  12. }
  13. public int getAge() {
  14. return age;
  15. }
  16. public void setAge(int age) {
  17. this.age = age;
  18. }
  19. }



 

5.3輸出圖片

Bundle01.java對應的界面如下:

 

點擊“Bundle Basic Data”、“Bundle Parcelable Data”、“Bundle Seriable Data”均跳轉到如下界面,但它們對應的logcat信息不同。


 

點擊“Bundle Basic Data”的logcat如下:


點擊“Bundle Parcelable Data”的logcat如下:


點擊“Bundle Seriable Data”的logcat如下:


轉自:http://www.cnblogs.com/skywang12345/archive/2013/03/06/3165555.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM