Android 数据传递-通过全局变量传递数据
Ø在Activity之间数据传递中还有一种比较实用的方式,就是全局对象,实用J2EE的读者来说都知道Java Web的四个作用域,
这四个作用域从小到大分别是Page、Request、Session和Application,其中Application域在应用程序的任何地方都可以使用
和访问,除非是Web服务器停止,Android中的全局对象非常类似于Java Web中的Application域,除非是Android应用程序清
除内存,否则全局对象将一直可以访问。
Ø案例一
package com.android.myapp; import android.R.integer; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class Main extends Activity { /** Called when the activity is first created. */ private Button button; private MyApp myApp; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); button = (Button)this.findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub myApp = (MyApp)getApplication(); myApp.setName("jack");//修改之后的名称 Intent intent = new Intent(Main.this,OtherActivity.class); startActivity(intent); } }); } }
package com.android.myapp; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; 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); textView = (TextView)this.findViewById(R.id.msg); myApp = (MyApp)getApplication(); textView.setText("-appname-->>"+myApp.getName()); } }
package com.android.myapp; import android.app.Application; public class MyApp extends Application { public String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); setName("张三"); } }
相关推荐
yangkang 2020-11-09
lbyd0 2020-11-17
sushuanglei 2020-11-12
85477104 2020-11-17
KANSYOUKYOU 2020-11-16
wushengyong 2020-10-28
lizhengjava 2020-11-13
星月情缘 2020-11-13
huangxiaoyun00 2020-11-13
luyong0 2020-11-08
腾讯soso团队 2020-11-06
Apsaravod 2020-11-05
PeterChangyb 2020-11-05
gaobudong 2020-11-04
wwwjun 2020-11-02
gyunwh 2020-11-02
EchoYY 2020-10-31
dingyahui 2020-10-30