简体   繁体   English

从另一个类访问公共变量?

[英]Accessing a public variable from another class?

The app I'm currently developing has more than one class created, with a corresponding .xml file for each. 我当前正在开发的应用程序创建了多个类,每个类都有一个对应的.xml文件。 My app requires progressing from one screen to the next after a calculation has been completed. 计算完成后,我的应用程序需要从一个屏幕转到下一个屏幕。

In one class, I have declared a public double called V, which is the result of a voltage calculation. 在一个类中,我声明了一个称为V的公共双精度数,它是电压计算的结果。

When the user presses "NEXT", a new class (ed: Activity?) is called, and the xml file will change the screen view to a new layout. 当用户按下“ NEXT”时,将调用一个新的类(ed:Activity?),并且xml文件会将屏幕视图更改为新的布局。

In this new class, I need to use the variable (double V) for a new calculation. 在这个新类中,我需要使用变量(double V)进行新的计算。

I thought that if a variable was public, it could be used anywhere in the package. 我认为,如果变量是公共变量,则可以在包中的任何位置使用它。 Do I need to import this variable, or re-declare it somehow? 我是否需要导入此变量,或以某种方式重新声明它?

Any answers would be much appreciated. 任何答案将不胜感激。 I've tried everything that I can think of, but Eclipse just keeps saying V cannot be resolved. 我已经尝试了所有我能想到的东西,但是Eclipse一直说V无法解析。

I'm assuming by "a new class is called", you're talking about launching a new Activity with an Intent, like so: 我假设通过“调用一个新类”,您正在谈论使用Intent启动一个新的Activity,如下所示:

Intent intent = new Intent(this, Activity2.class);
startActivity(intent);

Assuming this is the case, you can just pass the variable along as an extra in the Intent object, and then retrieve it from the newly launched Activity. 假设是这种情况,您可以将变量作为附加变量传入Intent对象,然后从新启动的Activity中检索它。 For example: 例如:

Intent intent = new Intent(this, Activity2.class);
intent.putExtra("voltage", V);
startActivity(intent);

Now, within your Activity2.java document, in your onCreate(), add this: 现在,在Activity2.java文档中的onCreate()中,添加以下内容:

Intent intent = getIntent();
double V;
//return -1 if unable to retrieve
if(intent != null) V = intent.getDoubleExtra("voltage", -1);

Then V should be populated with the correct voltage value. 然后,应使用正确的电压值填充V。

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

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