Android Programming The Big Nerd Ranch Guide, 3rd Edition

(Brent) #1

Chapter 11  Using ViewPager


226

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.


Challenge: Restoring CrimeFragment’s Margins


You may have noticed that your CrimeFragment has mysteriously lost its margins. In
fragment_crime.xml, you specified a margin of 16dp.


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:orientation="vertical">


That margin no longer shows up. So, what gives? ViewPager’s layout params do not support margins.
Update fragment_crime.xml and restore your margins.


Challenge: Adding First and Last Buttons


Add two buttons to CrimePagerActivity that allow jumping the ViewPager to the first or last crime
instantly. As a bonus, disable “jump to first” when on the first page and “jump to last” when on the last
page.

Free download pdf