Question

In Eclipse, anytime that I create a new Activity in my Android app, in addition to the Java Activity class, a companion layout xml file is also generated. Obviously, I could generate 10 layouts and switch the Activity's layout between these 10 anytime I want.

So, my question is why this layout is being generated; is it generated for convenience or is it a good practice to always have a specific layout associated with the Activity?

Also, does an Activity always have to have a layout, or that I could have an Activity that never uses a layout.

Was it helpful?

Solution

From android reference:

An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View).

This process of creating a window is costly operation and you should only call setContentView-once in your Activity.

  • If you feel the need to add xml-resources you can use a layout inflater. (tip: always pass a container reference to the inflater)
  • If you feel the need to use more then one layout file (a whole new ui), you should consider creating a new Activity.

About your questions:

So, my question is why this layout is being generated; is it generated for convenience or is it a good practice to always have a specific layout associated with the Activity?

Convenience, you are using a wizard for creating an Activity. In most cases you will implement an XML resource for your Activity, so the wizard creates it for you.

Also, does an Activity always have to have a layout, or could I have an Activity that never uses a layout?

It is not required to have a layout for an Activity, but a window will be created. An example of this is a splash screen Activity where you show an image but do not set a content View.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top