android Bundle的做用

解釋:Bundle類用做攜帶數據,它相似於Map,用於存放key-value名值對形式的值。相對於Map,它提供了各類經常使用類型的putXxx()/getXxx()方法,如:putString()/getString()和putInt()/getInt(),putXxx()用於往Bundle對象放入數據,getXxx()方法用於從Bundle對象裏獲取數據。Bundle的內部其實是使用了HashMap類型的變量來存放putXxx()方法放入的值:ide

public final class Bundle implements Parcelable, Cloneable {this

            ......對象

 Map mMap;get

 public Bundle() {it

       mMap = new HashMap();class

        ......變量

 }request

 public void putString(String key, String value) {請求

      mMap.put(key, value);方法

 }

public String getString(String key) {

       Object o = mMap.get(key);

        return (String) o;

        ........//類型轉換失敗後會返回null,這裏省略了類型轉換失敗後的處理代碼

}}

在調用Bundle對象的getXxx()方法時,方法內部會從該變量中獲取數據,而後對數據進行類型轉換,轉換成什麼類型由方法的Xxx決定,getXxx()方法會把轉換後的值返回。

 

舉例:使用Bundle在Activity間傳遞數據

[1].從源Activity 中傳遞數據

//數據寫入Intent
Intent openWelcomeActivityIntent=new Intent();
Bundle myBundelForName=new Bundle();
myBundelForName.putString("Key_Name",inName.getText().toString());
myBundelForName.putString("Key_Age",inAge.getText().toString());
openWelcomeActivityIntent.putExtras(myBundelForName);
openWelcomeActivityIntent.setClass(AndroidBundel.this, Welcome.class);
startActivity(openWelcomeActivityIntent);

 

目標Activity 中獲取數據

//從Intent 中獲取數據
Bundle myBundelForGetName=this.getIntent().getExtras();
String name=myBundelForGetName.getString("Key_Name");
myTextView_showName.setText("歡迎您進入:"+name);

 

使用Bundle在Activity間傳遞數據2

 

從源請求Activity 中經過一個Intent 把一個服務請求傳到目標Activity 中
 

private IntenttoNextIntent;//Intent 成員聲明
toNextIntent=new Intent();//Intent 定義
toNextIntent.setClass(TwoActivityME3.this, SecondActivity3.class);
//設定開啓的下一個Activity
startActivityForResult(toNextIntent, REQUEST_ASK);
//開啓Intent 時候,把請求碼同時傳遞

 

在源請求Activity 中等待Intent 返回應答結果,經過重載onActivityResult()方法

@Override protected void onActivityResult(int requestCode,int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); if(requestCode==REQUEST_ASK){ if(resultCode==RESULT_CANCELED){ setTitle("Cancel****"); }else if(resultCode==RESULT_OK){ showBundle=data.getExtras();//從返回的Intent中得到Bundle Name=showBundle.getString("myName");//從bundle中得到相應數據 text.setText("the name get from the second layout:\n"+Name); } } }

相關文章
相關標籤/搜索