在Android应用中使用全局变量,除了public的静态变量,还有更优雅的方式是使用android.app.Application。
启动Application时,系统会创建一个PID,即进程ID,所有的Activity就会在此进程上运行。那么我们在Application创建的 时候初始化全局变量,同一个应用的所有Activity都可以取到这些全局变量的值。
AndroidMenifest.xml
< application
android:name =".CombankDroid"
android:icon ="@drawable/first_aid"
android:label ="@string/app_name" >
</ application >
import android.app.Application;
public classOverAllData extends Application
{
privatefloatrealWidth;
publicfloatgetRealWidth()
{
return this.realWidth;
}
publicvoidsetRealWidth(floatr)
{
if(r > 0) this.realWidth = r;
}
@Override
publicvoidonCreate()
{
this.realWidth = 0.0f;
super.onCreate();
}
}
public class XXXActivity extends Activity
{
private OverAllData OAD;
protected void onCreate(Bundle savedInstanceState)
{
OAD = (OverAllData) getApplication();
float l = OAD.getRealWidth();
....
}
protected void XXX(XXX XXX)
{
float l = OAD.getRealWidth();
OAD.setRealWidth(l);
....
}
}