我正在主应用程序类中创建自定义类。让我们说我的 mainAccount
。
现在,我正在创建许多 Activity 。我想在每个 Activity 中使用 mainAccount
变量,我该怎么做?一种方法是输入 Intent 并传递给每个 Activity 。有没有更好的方法,比如让它成为全局性的等等?
最好的问候
最佳答案
查找Singleton classes .基本上,您想要这样的东西。
public class Singleton {
private static Singleton instance = null;
protected Singleton() {
// Exists only to defeat instantiation.
}
public static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
然后,对于任何需要访问该类的类,调用:
Singleton var=Singleton.getInstance();
这本质上是全局的,没有全局变量的大部分负面影响。它将确保该类只能存在一个对象,但每个需要它的人都可以访问它。
关于java - 声明一个全局变量以在所有 Activity 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9613055/