简体   繁体   中英

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. So, for example, if there is a value x = 5 in Activity1, that value would be passed into Activity2. Then, if the player changes x to 6 in Activity2, this information would be passed back into 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:

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.

I would add that variable in your Application class implementation, and access it as ((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. Subjects from RxJava can be very helpful for achieving it.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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