Android 全局变量 [英] Android global variable

查看:48
本文介绍了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;
    }
}

在您的 android manifest 中,您必须声明实现 android.app.Application 的类(将 android: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 全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆