在Activity中調用另一個Activity時,需要調用startActivity(Intent i), 若需要在調用另外一個Activity的同時傳遞資料,那麼就需要利用android.os.Bundle對象封裝資料的能力,将欲傳遞的資料或參數,通過Bundle來傳遞不同Intent之間的資料。Bundle對象針對了不同的資料類型提供了許多的方法,例如,傳遞String類型的資料,使用的方法為Bundle.putString(stringName,stringValue):
而要傳遞Double類型的資料,使用的方法為Bundle.putDouble(doubleName,doubleValue),如下:bundle.putDouble("height", heightNum);
下面這一段代碼是打包資料并傳遞:
Bundle bundle = new Bundle();
bundle.putString("name", nameStr);
bundle.putDouble("height", heightNum);
intent.putExtras(bundle);
startActivity(intent); |
在Activity2要如何接收來自Activity1傳遞來的資料呢?試想,在Activity1是以Bundle封裝對象,自然在Activity2亦是以Bundle的方式解開封裝的資料;程式中以getIntent().getExtras() 方法取得随着Bundle對象傳遞過來的資料。若要由Bundle對象中取出資料,則使用Bundle.getString(stringName)、Bundle.getDouble(doubleName) 等相對應的方法即可。
下面這段代碼用來解析傳遞過來的資料:
Bundle bundle = this.getIntent().getExtras();
String name = bundle.getString("name");
Double height = bundle.getDouble("height");
|
最後,還是用一個小程式來示範一下:
首先是 activity 1:
package com.zx.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class BundleTest extends Activity {
EditText nameWidget, heightWidget;
Button btnSubmit;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//get name and height
nameWidget = (EditText)findViewById(R.id.nameText);
heightWidget = (EditText)findViewById(R.id.heightText);
btnSubmit = (Button)findViewById(R.id.submit);
//btnSubmit.setOnClickListener(new Button.OnClickListener()
btnSubmit.setOnClickListener(new Button.OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String nameStr = null;
Double heightNum = 0.0;
nameStr = nameWidget.getText().toString();
heightNum = Double.parseDouble(heightWidget.getText().toString());
Log.i("zx", "name is " + nameStr + " height=" + heightNum);
Intent intent = new Intent();
intent.setClass(BundleTest.this, ResultPage.class);
Bundle bundle = new Bundle();
bundle.putString("name", nameStr);
bundle.putDouble("height", heightNum);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
}
|
接下來是第二個activity的代碼:
package com.zx.test;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ResultPage extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
Bundle bundle = this.getIntent().getExtras();
String name = bundle.getString("name");
Double height = bundle.getDouble("height");
TextView tv = (TextView)findViewById(R.id.TextView01);
tv.setText("your name is " + name + ", your height is "+ height.toString());
}
} |