本文介绍了Android的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能创建全局变量仍保留在应用程序中的生命周期价值,无论哪个活动运行。

How can I create global variable keep remain values around the life cycle of the application regardless which activity running..

推荐答案

您可以扩展基 android.app.Application 类,并添加成员变量,像这样:

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;
    }
}

在你的Andr​​oid清单必须声明类实现android.app.Application(添加'机器人:NAME =MyApplication的属性到现有的应用程序标记):

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();

这篇关于Android的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:31