Java 从另一个类更改变量值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18910816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:15:10  来源:igfitidea点击:

Changing Variable value from another class

javaandroidandengine

提问by VonnCC

I have an integer(levelstatus) in class A(LevelSelectScene) and I want to change it in class B(GameScene), is it possible?

levelstatus在 A( LevelSelectScene)类中有一个整数( ),我想在 B( GameScene)类中更改它,这可能吗?

here is my code:

这是我的代码:

(Code in GameScene)

(GameScene 中的代码)

public class levelComplete()
{

levelSelectScene.getInstance.levelstatus=1;

}

LevelSelectScenehas an public integer levelstatus.

LevelSelectScene有一个公共整数levelstatus

and after an event happens, levelCompletewill trigger and will change the value of levelstatusfrom null to 1.

并且在事件发生后,levelComplete将触发并将值levelstatus从 null更改为 1。

采纳答案by Suresh Atta

Yes.

是的。

Make your levelstatusvariable as static.

使您的levelstatus变量为static.

Because I guess you need to change that variable in each level class.

因为我猜您需要在每个级别类中更改该变量。

That means,you are wanting to access that variable through out the whole Game(All levels).

这意味着,您希望在整个游戏(所有级别)中访问该变量。

And also,Declare that variable in a Utilclass(proposing a name LevelUtil),Since it wont attach to a single level.

而且,在Util类中声明该变量(建议名称LevelUtil),因为它不会附加到单个级别。

回答by gorbos

I believe it is more appropriate if you look into SharedPrefences of the Android API.

如果您查看 Android API 的 SharedPrefences,我相信它更合适。

Check it here.

在这里检查。

It could be used across the whole project of yours and it is handy in those kind of cases.

它可以在您的整个项目中使用,并且在这种情况下很方便。

回答by NCA

It is possible to change the value any where in the project(that is in any class) since the variable is declared as public levelstatus.

由于变量被声明为public levelstatus.

If you want to change the value of the variable in many places and the new value should be the modification of previously changed value, the you should declare the variable as public static levelstatus.

如果要在很多地方更改变量的值,并且新值应该是对先前更改值的修改,则应将变量声明为public static levelstatus.

回答by R?dvan Nuri G??men

You can access your variable as a public static.

您可以将变量作为公共静态访问。

Definition:

定义:

public  static Boolean isPremium;

Access (do not forget import) :

访问(不要忘记import):

your_class.isPremium