Bundle类是一个key-value对,“A mappingfrom String values to various Parcelable types.”
两个activity之间的通讯可以通过Bundle类来实现,做法就是:
(1)新建一个Bundle类
Bundle bundle =new Bundle();
(2)Bundle类中加入数据(key -value的形式,另一个activity里面取数据的时候,就要用到key,找出对应的value)
bundle.putString("INFO","Hello");
(3)新建一个intent对象,并将该bundle加入这个intent对象
Intent intent = new Intent();
intent.setClass(TestBundle.this,Target.class);
intent.putExtras(mBundle);
(4)在另一个Activity中获得数据
Bundle bundle = getIntent().getExtras();
String data = bundle.getString("INFO");
sendActivity.java
package com.example.bundle_com;
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;
public class sendActivity extends Activity {
private Button sendButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
sendButton = (Button)findViewById(R.id.btn);
sendButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Bundle bundle = new Bundle();
bundle.putString("INFO","Hello" );
Intent intent = new Intent();
intent.setClass(sendActivity.this, receiveActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
}
receiveActivity.java
package com.example.bundle_com;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class receiveActivity extends Activity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.layout2);
textView = (TextView)findViewById(R.id.textView);
Bundle bundle = getIntent().getExtras();
String data = bundle.getString("INFO");
textView.setText(data);
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bundle_com"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.bundle_com.sendActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".receiveActivity"></activity>
</application>
</manifest>