简体   繁体   English

Android Studio-整个项目中的全局变量?

[英]Android Studio - Global variable throughout an entire project?

So I'm making a mobile game and have multiple activities throughout my project. 因此,我正在制作一款手机游戏,并且在我的整个项目中都有多项活动。 I have been passing variables from one activity to the next using Intents, and then passing these variables back to other activities. 我一直在使用Intent将变量从一个活动传递到下一个活动,然后将这些变量传递回其他活动。 So, for example, if there is a value x = 5 in Activity1, that value would be passed into Activity2. 因此,例如,如果Activity1中的值x = 5,则该值将传递到Activity2中。 Then, if the player changes x to 6 in Activity2, this information would be passed back into Activity1. 然后,如果玩家在Activity2中将x更改为6,则此信息将传递回Activity1。

This method works, but it seems very inefficient. 此方法有效,但效率似乎很低。 Is there any way to create a global variable for the entire project in such a way so when I change it in one activity, it changes in all the activities? 有什么方法可以为整个项目创建一个全局变量,以便当我在一个活动中更改它时,它在所有活动中都会更改吗?

Thanks 谢谢

Simple, create a singleton, store your variable there and then have your activities read from and write to the variable in the singleton. 简单,创建一个单例,将您的变量存储在那里,然后让您的活动在单例中读取和写入变量。

How to declare a singleton: 如何声明单例:

Kotlin: 科特林:

object MySingleton {
    var myVariable: Int = 0
}

Java: Java:

public class MySingleton {
    private int myVariable = 0;

    // Getter/setter

    private static MySingleton instance;

    public static MySingleton getInstance() {
        if (instance == null)
            instance = new MySingleton();
        return instance;
    }

    private MySingleton() { }
}

There are multiple ways to achieve that, some of them are according to good architecure practices, some of them are not. 有多种方法可以实现这一点,其中有些是根据良好的架构实践,而有些则不是。 Generally, Singleton pattern first pops on mind, but I would avoid Singleton since it is global state and anti-pattern. 通常,首先想到的是Singleton模式,但我会避免使用Singleton,因为它是全局状态和反模式。

I would add that variable in your Application class implementation, and access it as ((MyApplication) getApplication()).getMySharedVariable() 我将在您的Application类实现中添加该变量,并以((MyApplication) getApplication()).getMySharedVariable()

What can be even better, you can make that variable accessible trough listener (using Listener or Publish/Subscribe pattern) so whoever wants, they may subscribe to all changes that happen with your variable and react upon it imediatelly. 甚至更好的是,您可以使该变量可通过槽式侦听器访问(使用Listener或Publish / Subscribe模式),因此无论谁愿意,他们都可以订阅变量发生的所有更改并立即对其进行响应。 Subjects from RxJava can be very helpful for achieving it. RxJava的主题对于实现它非常有帮助。

Given your requirements: 根据您的要求:

public class X {
    public static int val = 0;
}

and

{
   X.val = 5;
}

Of course this is naive - but if you have more requirements you should specify them. 当然这是幼稚的-但是如果您有更多要求,则应指定它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM