Activity詳解二 activity資料傳遞,activity詳解

來源:互聯網
上載者:User

Activity詳解二 activity資料傳遞,activity詳解

首先看:

 

1.Bundle類的作用

  Bundle類用作攜帶資料,它類似於Map,用於存放key-value名值對形式的值。相對於Map,它提供了各種常用類型的putXxx()/getXxx()方法,如:putString()/getString()和putInt()/getInt(),putXxx()用於往Bundle對象放入資料,getXxx()方法用於從Bundle對象裡擷取資料。Bundle的內部實際上是使用了HashMap<String, Object>類型的變數來存放putXxx()方法放入的值。簡單地說,Bundle就是一個封裝好的包,專門用於匯入Intent傳值的包。

2.為Intent附加資料的兩種寫法

  第一種寫法,用於大量新增資料到Intent:

Intentintent = new Intent();

  Bundle bundle = new Bundle();//該類用作攜帶資料

  bundle.putString("name","Alice");

  intent.putExtras(bundle);//為意圖追加額外的資料,意圖原來已經具有的資料不會丟失,但key同名的資料會被替換

  第二種寫法:這種寫法的作用等價於上面的寫法,只不過這種寫法是把資料一個個地添加進Intent,這種寫法使用起來比較方便,而且只需要編寫少量的代碼。

  Intent intent = new Intent();

  intent.putExtra("name","XXX");

  那麼,這兩種方法有什麼區別呢?

  完全沒有區別。當你調用putExtras()方法時,所傳入的Bundle會被轉化為Intent的索引值(別忘了Intent也以索引值模式轉載資料)。

  那麼,現在看看如何將Intent和Bundle取出來。

  方法很簡單,直接使用this.getIntent()就可以得到傳來的Intent,然後在這個Intent的基礎上調用getExtras()就可以得到Bundle。然後這個Bundle你想要什麼得到什麼就get什麼。

  比如String str=bundle.getString("USERNAME"); 就是得到鍵為“USERNAME”的字串,int num=bundle.getInt("Number");就是得到鍵為“Number”的整型。

android中的組件間傳遞的對象一般實現Parcelable介面,當然也可以使用java的Serializable介面,前者是android專門設計的,效率更高,下面我們就來實現一個Parcelabel。

1. 建立一個類實現Parcelable介面,具體實現如下:

public class ParcelableData implements Parcelable{      private String name;      private int age;      public ParcelableData(){          name = "guest";          age = 20;      }      public ParcelableData(Parcel in){          //順序要和writeToParcel寫的順序一樣          name = in.readString();          age = in.readInt();      }      public String getName(){          return name;      }      public void setName(String name){          this.name = name;      }            public int getAge(){          return age;      }      public void setAge(int age) {          this.age = age;      }      @Override      public int describeContents() {          // TODO Auto-generated method stub          return 0;      }      @Override      public void writeToParcel(Parcel dest, int flags) {          // TODO Auto-generated method stub          dest.writeString(name);          dest.writeInt(age);      }      public static final Parcelable.Creator<ParcelableData> CREATOR = new Parcelable.Creator<ParcelableData>() {          public ParcelableData createFromParcel(Parcel in) {              return new ParcelableData(in);          }          public ParcelableData[] newArray(int size) {              return new ParcelableData[size];          }      };  }  

 

2. 通過下面的方法發送對象。Bundle類也實現了Parcelable介面,一般在android中我們是通過Bundle來封裝資料並進行傳送的。

Intent intent = new Intent();  intent.setClass(this, SubActivity.class);  // 直接添加  //intent.putExtra("MyData", new ParcelableData());    // 通過Bundle  Bundle bundle = new Bundle();  bundle.putString("MyString", "test bundle");  bundle.putParcelable("MyData", new ParcelableData());  intent.putExtras(bundle);  startActivity(intent);  

 

 

3. 下面的接收對象的方法。

//ParcelableData parcelableData = getIntent().getParcelableExtra("MyData");  Bundle bundle = getIntent().getExtras();  ParcelableData parcelableData = bundle.getParcelable("MyData");  String testBundleString = bundle.getString("MyString");  Log.v("string=", testBundleString);  Log.v("name=", parcelableData.getName());  Log.v("age=", ""+parcelableData.getAge());  
 3 DEMO下載

activity代碼:

package mm.shandong.com.testbundle;import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.text.TextUtils;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.EditText;import android.widget.Toast;import java.util.ArrayList;import mm.shandong.com.testbundle.entity.Person;public class TestBundleActivity extends AppCompatActivity {    EditText editText1;    EditText editText2;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_test_bundle);        editText1 = (EditText) findViewById(R.id.editText1);        editText2 = (EditText) findViewById(R.id.editText2);    }   ///提交選擇的地區,並把地區傳遞給TestBundleActivity3    public void submitRegion(View view) {        EditText editTextRegion = (EditText) findViewById(R.id.editTextRegion);        Intent intent = new Intent(this, TestBundleActivity3.class);        String region = editTextRegion.getText().toString();        if (!TextUtils.isEmpty(region)) {            intent.putExtra("region", region);            startActivity(intent);        } else {            Toast.makeText(this, "地區不能是空值", Toast.LENGTH_SHORT).show();        }    }    ///把需要計算的兩個值都是Integer類型,傳入到TestBundleActivity1    public void calculte(View view) {        Intent intent = new Intent(this, TestBundleActivity1.class);        Bundle bundle = new Bundle();        String first = editText1.getText().toString();        String second = editText2.getText().toString();        if (!TextUtils.isEmpty(first) && !TextUtils.isEmpty(second)) {            bundle.putInt("first", Integer.parseInt(first));            bundle.putInt("second", Integer.parseInt(second));            intent.putExtras(bundle);            startActivity(intent);        } else {            Toast.makeText(this, "數值不能是空", Toast.LENGTH_SHORT).show();        }    }    ///傳遞Serializable對象到TestBundleActivity2    public void login(View view) {        EditText editTextName = (EditText) findViewById(R.id.editTextName);        EditText editTextCode = (EditText) findViewById(R.id.editTextCode);        Intent intent = new Intent(this, TestBundleActivity2.class);        Bundle bundle = new Bundle();        String name = editTextName.getText().toString();        String code = editTextCode.getText().toString();        if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(code)) {            Person person = new Person();            person.setName(name);            person.setCode(code);            bundle.putSerializable("person", person);            intent.putExtras(bundle);            startActivity(intent);        } else {            Toast.makeText(this, "姓名編號不能是空", Toast.LENGTH_SHORT).show();        }    }}

 

最後,以上例子都來源與安卓無憂,請去應用寶或者豌豆莢下載:http://android.myapp.com/myapp/detail.htm?apkName=com.shandong.mm.androidstudy,源碼例子文檔一網打盡。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.