Android Application 创建全局变量
以前都是建立一个ConstData的类来保存全局用的变量,但是有时候确实是有点小问题。
所以研究了一下使用Application来建立全局变量,下面就是代码,主要分为四个文件:
(1)是MyApplication类,保存全局变量以及变量的查询和修改
(2)TestAndroid 类 也是主类
(3)otherActivity 另外一个类调用全局变量试试是不是被主类改变了
(4)manifest.xml文件
MyApplication
- package an.test.android;
- import android.app.Application;
- public class MyApp extends Application{
- private String mylabel ;
- public String getLabel(){
- return mylabel;
- }
- public void setLabel(String s){
- this.mylabel = s;
- }
- @Override
- public void onCreate() {
- // TODO Auto-generated method stub
- super.onCreate();
- setLabel("Welcome!"); //初始化全局变量
- }
- }
- package an.test.android;
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.util.Log;
- public class TestAndroid extends Activity {
- /** Called when the activity is first created. */
- private MyApp myApp;
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- myApp = (MyApp) getApplication(); //获得自定义的应用程序MyApp
- Log.i("guoll", "InitLabel:"+myApp.getLabel()); //将我们放到进程中的全局变量拿出来,看是不是我们曾经设置的值
- myApp.setLabel("Changing!"); //修改一下
- Log.i("guoll", "ChangeLabel:"+myApp.getLabel()); //看下,这个值改变了没有
- Intent intent = new Intent(); //再看一下在另一个Activity中是取到初始化的值,还是取到修改后的值
- intent.setClass(this, otherActivity.class);
- startActivity(intent);
- }
- }
- package an.test.android;
- import android.app.Activity;
- import android.os.Bundle;
- import android.util.Log;
- public class otherActivity extends Activity{
- private MyApp myApp;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- myApp = (MyApp) getApplication(); //获得自定义的应用程序MyApp
- Log.i("guoll", "OhterActivity receive the Label:"+myApp.getLabel()); //查看变量值是否修改了
- }
- }
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="an.test.android"
- android:versionCode="1"
- android:versionName="1.0">
- <application android:icon="@drawable/icon" android:label="@string/app_name" android:name="MyApp" >
- <activity android:name=".TestAndroid"
- 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=".otherActivity">
- </activity>
- </application>
- </manifest>
android:name="MyApp"
但是这个是必须的!
相关推荐
IT之家 2020-03-11
graseed 2020-10-28
zbkyumlei 2020-10-12
SXIAOYI 2020-09-16
jinhao 2020-09-07
impress 2020-08-26
liuqipao 2020-07-07
淡风wisdon大大 2020-06-06
yoohsummer 2020-06-01
chenjia00 2020-05-29
baike 2020-05-19
扭来不叫牛奶 2020-05-08
hxmilyy 2020-05-11
黎豆子 2020-05-07
xiongweiwei00 2020-04-29
Cypress 2020-04-25
冰蝶 2020-04-20