Android全局变量
如何在应用程序的生命周期中创建全局变量keep keep values而不管哪个活动正在运行..
你可以扩展基类android.app.Application
类并添加成员变量,如下所示:
public class MyApplication extends Application {
private String someVariable;
public String getSomeVariable() {
return someVariable;
}
public void setSomeVariable(String someVariable) {
this.someVariable = someVariable;
}
}
在您的android清单中,您必须声明实现android.app.Application的类(将android:name=".MyApplication"
属性添加到现有应用程序标记中):
<application
android:name=".MyApplication"
android:icon="@drawable/icon"
android:label="@string/app_name">
然后在你的活动中,你可以像这样获取和设置变量:
// set
((MyApplication) this.getApplication()).setSomeVariable("foo");
// get
String s = ((MyApplication) this.getApplication()).getSomeVariable();
你可以像这样使用一个Singleton Pattern
:
package com.ramps;
public class MyProperties {
private static MyProperties mInstance= null;
public int someValueIWantToKeep;
protected MyProperties(){}
public static synchronized MyProperties getInstance() {
if(null == mInstance){
mInstance = new MyProperties();
}
return mInstance;
}
}
在你的应用程序中,你可以用这种方式访问你的单身人士:
MyProperties.getInstance().someValueIWantToKeep
这个全局变量适用于我的项目:
public class Global {
public static int ivar1, ivar2;
public static String svar1, svar2;
public static int[] myarray1 = new int[10];
}
// How to use other or many activity
Global.ivar1 = 10;
int i = Global.ivar1;
链接地址: http://www.djcxy.com/p/43373.html
下一篇: How do I use extern to share variables between source files?