使用意图进行数据的传递这里用到的方法是全局变量方法。
整体思路:首先定义一个继承Application的全局变量类,在类中定义一些字段和get、set方法;第一个活动定义一个全局变量对象,设置它的值,跳转到第二个活动;在第二个活动获取这个全局变量,并得到里面的字段,这样就完成了数据传递。
acitivity_mian.xml文件:
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="使用Application传递数据" />
other.xml文件:
<TextView
android:id="@+id/msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
MyApp.java文件:
public class MyApp extends Application {
public String name;//全局变量,在应用程序的任何地方都可以取到这个值
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
setName("张三");
}
}
MainActivity.java文件:
private Button button;
private MyApp myApp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
myApp=(MyApp)getApplication();
myApp.setName("jack");
Intent intent=new Intent(MainActivity.this,OtherActivity.class);
startActivity(intent);
}
});
OtherActivity.java文件:
private TextView textView;
private MyApp myApp;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.other);
textView=(TextView)findViewById(R.id.msg);
myApp=(MyApp)getApplication();
textView.setText("-appname-->>"+myApp.getName());
}