为什么不干将preferred活动之间的访问变量时? [英] Why aren't getters preferred when accessing variables between activities?
问题描述
每日有以下<一许多问题href="http://stackoverflow.com/questions/10978788/how-to-share-variables-between-classes-in-java#comment14339055_10978788">type对这样:
我如何从另一个活动的变量
?
答案通常推荐使用共享preferences
或 Intent.putExtra()
。
在我看来,的getter
的方法是什么将是从另一个类访问变量的方法。毕竟,活动
正在考虑之中的是一个类,它的变量是类成员。
To me, a getter
method is what would be an approach to access a variable from another class. After all, the Activity
that is under consideration is a class, and it's variables are class members.
为什么不吸气剂pferred像共享preferences或意向额外途径方法$ P $?
我说的是那些需要访问活动之间的变量简单的情况下,例如这一个:
I'm talking about simple situations that require accessing a variable between activities, for example this one:
class OneClass extends Activity {
int a;
..
// some changes to a
..
}
然后在另一个类(活动
):
class SomeOtherClass extends Activity {
..
// trying to access a here
..
}
是一个的getter
方法的正确的方法在这里,或不?
Is a getter
method a correct approach here, or not?
再次 - 我不是在谈论场景,这些东西其实都是正确的道路要走。 共享preferences
为数据量小,演员
的文件说,持久性存储:此可以用来提供扩展信息到组件。举例来说,如果我们要发送的电子邮件消息的行动,我们可能还包括额外碎片这里的数据提供一个主题,正文等。的
Again - I'm not talking about scenarios where these things are actually the right way to go. SharedPreferences
for persistent storage of small amount of data, extras
as the documentation says : This can be used to provide extended information to the component. For example, if we have a action to send an e-mail message, we could also include extra pieces of data here to supply a subject, body, etc.
由于有些问题的答案可能已经表示,有像不能保证其他活动
活着,我想有某些情况下更可能的,正确的理由,以为什么人们建议去的意图和共享preferences。
As some of the answers have likely indicated that there are certain scenarios like no guarantee of the other Activity
being alive, I guess there are more probable and correct reasons as to why people suggest going for intents and shared preferences.
推荐答案
在回答你的问题是双重的:
The answer to your question is two fold:
- 对于元方面,属于对元所以无论如何,很多新手程序员看到的Android,想要写的应用程序,并吮吸的Java。
- 对于其他quesiton,通常使用getter和setter将无法正常工作,因为你不能以简单的方式传递活动的对象。虽然技术上可以做到这一点的,Parcelable,但不推荐,而更好的办法是使用意向的应用程序组件之间传递数据。
- 还有一点这突出的是,Android应用程序应该保持国家内部部件的最小量。我想,这一直是Android系统大获成功。如果你看一下应用程序在那里,有平均有很多不是用Java编写的典型程序较少的全局状态。的程序也更小,这是可以预料的,但事实上,一个原子活动可以重新present单个画面的任何一个画面中通常将不会持续的状态下,而事实上,在整个多态整个应用程序,导致应用程序组件之间的良好的逻辑分离。
这篇关于为什么不干将preferred活动之间的访问变量时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!