1.通过全局变量来传递。
新建一个全局的类继承于Application
package com.example.helloworld; import android.app.Application; public class MyApp extends Application {
public String passData; public String getPassData() {
return passData;
} public void setPassData(String passData) {
this.passData = passData;
} @Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
setPassData("default");
}
}
在首次展现的窗口中设置全局变量值。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "onCreate被执行了.");
button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
myapp = (MyApp) getApplication();
myapp.setPassData("全局变量");
Intent intent = new Intent(MainActivity.this,
OtherActivity.class);
startActivity(intent);
}
});
}
新建个窗体来接受全局变量值。
public class OtherActivity extends Activity {
private MyApp myapp;
private TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.other);
myapp=(MyApp)getApplication();
String data=myapp.getPassData();
textview=(TextView)this.findViewById(R.id.msg);
textview.setText(data);
}
}
然后在AndroidManifest.xml中配置下新的窗口,和全局变量名称
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" /> <application
android:name="com.example.helloworld.MyApp"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.helloworld.MainActivity"
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="com.example.helloworld.OtherActivity"></activity>
</application> </manifest>
OK,可以顺利传递全局变量数据。
2.通过剪切板来传递数据。