Bundle 是 Android 用來在不同 Activity 之間傳遞資料的容器,本質上是一組 key-value 映射,並可序列化,因此能隨 Intent 一起送過來。
package Android2.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Android2Activity extends Activity {
private EditText et = null;
private Button button = null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et = (EditText)findViewById(R.id.edit);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new ButtonListener());
}
public class ButtonListener implements OnClickListener{
public void onClick(View arg0) {
Bundle bundle = new Bundle();
bundle.putString("Name", et.getText().toString());
Intent intent = new Intent(Android2Activity.this, bundle.class);
intent.putExtras(bundle);
startActivity(intent);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="start"/>
</LinearLayout>
package Android2.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class bundle extends Activity{
private TextView text = null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.bundle);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
text = (TextView)findViewById(R.id.text);
text.setText(bundle.getString("Name"));
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
兩個實作上的小提醒:接收端最好用 containsKey 先判斷,或直接用 getString("Name", "") 的重載版本,避免 key 不存在時拿到 null 造成空指針;另外別忘了在新的 Activity 於 AndroidManifest.xml 中註冊,否則會 ActivityNotFoundException。Bundle 適合傳小型資料,若要傳大量內容,應改用其他機制。