简体   繁体   English

通常应将View和ViewGroups声明为Activity中的实例还是局部变量?

[英]Should Views and ViewGroups conventionally be declared as instance or local variables in Activities?

It doesn't seem as intuitive to decide which variables should be instance variables and which should be locally declared in classes that extend Activity to me as for other types of objects. 决定哪些变量应该是实例变量,哪些应该在将Activity扩展给我的类中本地声明,就像其他类型的对象一样,似乎并不直观。

For classes that DO extend Activity, where do you declare the Views and ViewGroups , assuming declaring them both in the onCreate() method and as instance variables works. 对于要扩展Activity的类,假设在onCreate()方法和实例变量中都声明了它们,则在哪里声明ViewsViewGroups Which is the convention? 哪个惯例?

So classes that extend Activity aren't like the everyday objects we deal with where it's pretty easy to distinguish which variables should be instance variables and which should be locally declared. 因此,扩展Activity的类与我们所处理的日常对象不同,在其中很容易区分哪些变量应该是实例变量,哪些应该在本地声明。

Sure they are. 当然可以。 Declare them where you need them. 在需要它们的地方声明它们。 If you only need to access them in certain methods to say set text or something then declare them there. 如果只需要使用某些方法访问它们以说出设置文本或其他内容,则可以在其中声明它们。 If you need them in multiple methods then declare them as member variables. 如果您需要多种方法使用它们,则将它们声明为成员变量。

assuming declaring them both in the onCreate() method and as instance variables works. 假设在onCreate()方法和实例变量中都声明了它们。

Why would you declare them in two places? 为什么要在两个地方声明它们?

Which is the convention? 哪个惯例?

See the first part of this answer. 请参阅此答案的第一部分。 Typically I declare them as member variables and initialize them in onCreate() because I seem to need them in multiple places and I like having them in one place. 通常,我将它们声明为成员变量,并在onCreate()对其进行初始化,因为我似乎需要将它们放在多个位置,而且我喜欢将它们放在一个位置。

Just make sure you initialize them after calling setContentView() or they will be null . 只要确保调用setContentView() 之后初始化它们否则它们将为null

Activity in Android represents part of UI object, lets say "window" . Android Activity代表UI对象的一部分,我们说"window" Activity has some components - layout with Views . 活动具有一些组成部分-使用Views布局。

If you want to use your views in many methods of your activity class then declare them as instance variables. 如果要在activity类的许多方法中使用视图,则将其声明为实例变量。 Because finding them with findViewById will be done only once. 因为使用findViewById查找它们只会执行一次。 And then you can use them many times just by using instance variables. 然后,仅通过使用实例变量就可以多次使用它们。

If you make your views references local their scopes will be narrowed. 如果您将视图引用本地化,则其范围将缩小。

If the activity holds the Views/View groups it's recommended to declare them as private members in the activity class. 如果活动包含视图/视图组,建议在活动类中将它们声明为私有成员。

Simply as is :) 就是这样:)

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

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