zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    visio中插入顶边大括号
    undefined reference to `SetPduPowerConsumptionCnt'的解决办法
    JMS : Java Message Service (Java消息服务)
    C#自己编写的一个函数 可以删除字符串中指定开头和结尾中间的字符串
    完全JSP分页代码
    用ASP+Access创建网站RSS格式内容摘要
    微软考试杭州考点
    split 分隔字符串
    JSP连接SQL Server 2000系统配置
    全球测试管理系统TestDirector(上)
  • 原文地址:https://www.cnblogs.com/wjune-0405/p/11946843.html
Copyright © 2011-2022 走看看