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

StackOverflow https://stackoverflow.com/questions/21650334

  •  08-10-2022
  •  | 
  •  

Domanda

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.

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. Which is the convention?

È stato utile?

Soluzione

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.

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.

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.

Just make sure you initialize them after calling setContentView() or they will be null.

Altri suggerimenti

Activity in Android represents part of UI object, lets say "window". Activity has some components - layout with Views.

If you want to use your views in many methods of your activity class then declare them as instance variables. Because finding them with findViewById will be done only once. 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 :)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top