Android global variable
如何在应用程序的生命周期中创建全局变量keep keep values而不管哪个活动正在运行..
You can extend the base android.app.Application
class and add member variables like so:
public class MyApplication extends Application {
private String someVariable;
public String getSomeVariable() {
return someVariable;
}
public void setSomeVariable(String someVariable) {
this.someVariable = someVariable;
}
}
In your android manifest you must declare the class implementing android.app.Application (add the android:name=".MyApplication"
attribute to the existing application tag):
<application
android:name=".MyApplication"
android:icon="@drawable/icon"
android:label="@string/app_name">
Then in your activities you can get and set the variable like so:
// set
((MyApplication) this.getApplication()).setSomeVariable("foo");
// get
String s = ((MyApplication) this.getApplication()).getSomeVariable();
You can use a Singleton Pattern
like this:
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;
}
}
In your application you can access your singleton in this way:
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/43374.html
上一篇: Haskell:列表,数组,向量,序列
下一篇: Android全局变量