For the More Curious: Laying Out Views in Code

Throughout this book, you have been creating your views in layout files. It is also possible to create your views in code.

In fact, you could have defined your ViewPager in code without a layout file at all:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ViewPager viewPager = new ViewPager(this);
    setContentView(viewPager);
    ...
}

No magic is necessary to create a view: Just call its constructor, passing in a Context as the parameter. You can programmatically create an entire view hierarchy instead of using layout files.

However, creating views in code should be avoided, because layout files provide a few benefits.

One benefit of layout files is that they help to provide a clear separation between your controller and view objects in your app. The view exists in XML and the controller exists in Java code. This separation makes your code easier to maintain by limiting the amount of changes in your controller when you change your view and vice versa.

Another benefit to views defined in XML is that you can use Android’s resource qualification system to automatically choose the appropriate version of that XML file based on the properties of the device.

As you saw in Chapter 3, this system makes it easy to change your layout file depending on the orientation of the device (as well as other configurations).

So what are the downsides to using layout files? Well, you do have to go to the trouble of creating an XML file and inflating it. If you are creating a single view, sometimes you may not want to go to the trouble.

Otherwise, though, there are no downsides to speak of – the Android team has never recommended constructing view hierarchies programmatically, even back in the old days when developers had to be even more conscious of performance than they are now. Even if you need something as small as an ID on your view (which is often necessary, even with a programmatically created view), it is simpler to have a layout file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.87.209.162