全局变量或任何建议 [英] Global variable or any suggestions
问题描述
您好,我正在开发基于Android的餐厅菜单。我的问题是tablenumber的设置。我怎样才能设置一个表号然后将它传递给各个类?
我尝试了什么:
我已经尝试了全局类,但是我无法使它工作。
Hello, I'm developing an android based restaurant menu. My problem is the setting of tablenumber. How can I set a table number then pass it around the classes?
What I have tried:
I've tried global classes, but I can't make it work.
推荐答案
怎么样?
How about?
public static int tableNumber;
这是可以访问的。在主活动中设置可以帮助您满足需要。但由于这是Android,因此有一种更简单,更简洁的方式将数据传递给另一个活动,例如,
This would be accessible. Setting it in the main activity may help you in what you need. But since this is Android, there is a much easier and cleaner way of passing the data to another activity, like this,
// Create the intent
Intent activity = new Intent(this, SecondActivity.class);
// Set the data
activity.putExtra("tableNumber", 1234);
// Start the activity
startActivity(activity);
稍后,在第二个活动中,您可以从启动此活动的意图中获取值。
Later, on the second activity you can get the value from the intent that started this activity.
Intent previousActivity = getIntent();
// Get the value
int tableNumber = previousActivity.getIntExtra("tableNumber", 0);
在我看来,这是将值和数据从一个活动共享到另一个活动的高效方式。尽管静态变量可能有效,但建议不要将数据从一个活动传递到另一个活动。
我打算写一篇关于此的文章,但由于它还没有,你可能想要阅读这篇文章。 android - 如何使用putExtra()和getExtra()作为字符串数据 - 堆栈溢出 [ ^ ]
使用全局任何东西都是一个非常糟糕的主意。
首先考虑对应用程序的许多地方共享的单个对象的引用是一些本地对象,其引用传递给应该使用它的所有类型/方法。如果你仔细计划的话,这很可能。
我明白这可能是一项艰苦的工作。然后你可以考虑第二种选择:单身模式。
请参阅:
单身模式 - 维基百科,免费的百科全书 [ ^ ],
Simply Singleton | JavaWorld [ ^ ]。
-SA
Using anything global is a really bad idea.
First thing to consider for having a reference to one single object shared in many places of your application is some local object with reference passed along to all types/methods where it should be used. This is quite possible, if you plan it thoroughly.
I understand that this could be a bit too much of painstaking work. Then you can consider the second option: singleton pattern.
Please see:
Singleton pattern — Wikipedia, the free encyclopedia[^],
Simply Singleton | JavaWorld[^].
—SA
这篇关于全局变量或任何建议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!