Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Creating Dynamic UI with Android Fragments
Creating Dynamic UI with Android Fragments

Creating Dynamic UI with Android Fragments: Make your Android apps a superior, silky-smooth experience for the end-user with this comprehensive guide to creating a dynamic and multi-pane UI. Everything you need to know in one handy volume.

eBook
€22.99 €25.99
Paperback
€32.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Creating Dynamic UI with Android Fragments

Chapter 1. Fragments and UI Modularization

This chapter introduces fragments, UI modularization, and the role fragments play in developing a modularized UI. The chapter demonstrates creating simple fragments and using fragments statically within activities.

Let us have a look at the topics to be covered:

  • The need for UI modularization

  • Fragments are the foundation of modularization

  • Support for fragments across Android versions

  • Creating fragments

By the end of this chapter, we will be able to create and use fragments within a static activity layout.

The need for a new approach to UI creation


Chances are that the first class you learned to use when you became an Android developer was the Activity class. After all, the Activity class provided your app with a user interface. By organizing your user interface components onto an activity, the activity became the canvas on which you were painting your application masterpiece.

In the early days of Android, building an application's user interface directly within an activity worked reasonably well. The majority of early applications had a relatively simple user interface and the number of different Android device form factors was small. In most cases, with the help of a few layout resources, a single activity worked fine across different device form factors.

Today, Android devices come in a wide variety of form factors with incredible variation in their size and shape. Combine this with the rich, highly interactive user interfaces of modern Android applications, and the creation of a single activity that effectively manages the user interface across such divergent form factors becomes extremely difficult.

A possible solution is to define one activity to provide the user experience for a subset of device form factors; for example, smartphones. Then define another activity for a different subset of form factors such as tablets. The problem with this approach is that activities tend to have a lot of responsibilities beyond simply rendering the user interface. With multiple activities performing essentially the same tasks, we must either duplicate the logic within each of the activities, or increase the complexity of our program by finding ways to share the logic across the activities. The approach of using different activities for different form factors also substantially increases the number of activities in the program, easily doubling or tripling the number of activities required.

We need a better solution. We need a solution that allows us to modularize our application user interface into sections that we can arrange as needed within an activity. Fragments are that solution.

Android fragments allow us to partition the user interface into functional groupings of user interface components and logic. An activity can load and arrange the fragments as needed for a given device form factor. The fragments take care of the form factor details while the activity manages the overall user interface issues.

The broad platform support of fragments

The Fragment class was added to Android at API Level 11 (Android 3.0). This was the first version of Android that officially supported tablets. The addition of tablet support exacerbated an already difficult problem; developing Android applications was becoming increasingly difficult because of the wide variety of Android device form factors.

Fortunately, fragments provide a solution to the problem. With fragments, we can much more easily create applications that support a variety of form factors, because we can partition our user interfaces into effective groupings of components and their associated logic.

There was one problem with fragments. Up until very recently, the majority of Android devices had an API Level below 11 and therefore didn't support fragments. Fortunately, Google released the Android Support Library, available at http://developer.android.com/tools/extras/support-library.html, which makes fragments available to any device running API Level 4 (Android 1.6) or above. With the Android Support Library, fragments are now available to virtually every Android device in use.

Note

Applications created with Android Studio automatically include the Android Support Library, and therefore support fragments on virtually all SDK versions in use. If you will be using a development tool other than Android Studio to create applications that target devices running on a SDK level below 11, see the Android Developers Blog post, Fragments For All, available at http://android-developers.blogspot.com/2011/03/fragments-for-all.html, for directions on manually adding the Android Support Library to your projects.

Fragments simplify common Android tasks

Fragments not only simplify the way we create our application user interfaces but they also simplify many of the built-in Android user interface tasks. User interface concepts such as tabbed displays, list displays, and dialog boxes have all historically had distinctly different approaches. When we think about it, though, they are all variations on a common concept, that is, combining user interface components and logic into a functional group. Fragments formalize this concept, and therefore allow us to take a consistent approach to these formerly disparate tasks. We talk about each of these issues in detail as well as some of the specialized fragment classes such as the DialogFragment class and the ListFragment class later in this book.

The relationship between fragments and activities

Fragments do not replace activities but rather supplement them. A fragment always exists within an activity. An activity instance can contain any number of fragments but a given fragment instance can only exist within a single activity. A fragment is closely tied to the activity on which it exists and the lifetime of that fragment is tightly coupled to the lifetime of the containing activity. We'll talk much more about the close relationship between the lifetime of a fragment and the containing activity in Chapter 3, Fragment Lifecycle and Specialization.

One thing we don't want to do is make the common mistake of overusing fragments. So often when someone learns about fragments, they make the assumption that every activity must contain fragments, and that's simply not the case.

As we go through this book, we'll discuss the features and capabilities of fragments and a variety of scenarios where they work well. We'll always want to keep those in mind as we're building our applications. In those situations where fragments add value, we definitely want to use them. However, it is equally important that we avoid complicating our applications by using fragments in those cases where they do not provide value.

Making the shift to fragments


Although fragments are a very powerful tool, fundamentally they do something very simple. Fragments group user interface components and their associated logic. Creating the portion of your user interface associated with a fragment is very much like doing so for an activity. In most cases, the view hierarchy for a particular fragment is created from a layout resource; although, just as with activities, the view hierarchy can be programmatically generated.

Creating a layout resource for a fragment follows the same rules and techniques as doing so for an activity. The key difference is that we're looking for opportunities to partition our user interface layout into manageable subsections when working with fragments.

The easiest way to get started working with fragments is for us to walk through converting a traditional activity-oriented user interface to use fragments.

The old thinking – activity-oriented

To get started, let's first look at the appearance and structure of the application we're going to convert. This application contains a single activity that, when run, looks like the following screenshot:

The activity displays a list of five book titles in the top portion of the activity. When the user selects one of those books titles, the description of that book appears in the bottom portion of the activity.

Defining the activity appearance

The appearance of the activity is defined in a layout resource file named activity_main.xml that contains the following layout description:

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

  <!-- List of Book Titles -->
  <ScrollView
      android:layout_width="match_parent"
      android:layout_height="0dp"
      android:id="@+id/scrollTitles"
      android:layout_weight="1">
    <RadioGroup
        android:id="@+id/bookSelectGroup"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
    >
      <RadioButton
          android:id="@+id/dynamicUiBook"
          android:layout_height="wrap_content"
          android:layout_width="wrap_content"
          android:text="@string/dynamicUiTitle"
          android:checked="true" />
      <RadioButton
          android:id="@+id/android4NewBook"
          android:layout_height="wrap_content"
          android:layout_width="wrap_content"
          android:text="@string/android4NewTitle" />

      <!-- Other RadioButtons elided for clarify -->

    </RadioGroup>
  </ScrollView>

  <!-- Description of selected book -->
  <ScrollView
      android:layout_width="match_parent"
      android:layout_height="0dp"
      android:id="@+id/scrollDescription"
      android:layout_weight="1">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/dynamicUiDescription"
        android:id="@+id/textView"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:gravity="fill_horizontal"/>
  </ScrollView>
</LinearLayout>

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

This layout resource is reasonably simple and is explained as follows:

  • The overall layout is defined within a vertically-oriented LinearLayout element containing the two ScrollView elements

  • Both of the ScrollView elements have a layout_weight value of 1 that causes the top-level LinearLayout element to divide the screen equally between the two ScrollView elements

  • The top ScrollView element, with the id value of scrollTitles, wraps a RadioGroup element containing a series of the RadioButton elements, one for each book

  • The bottom ScrollView element, with the id value of scrollDescription, contains a TextView element that displays the selected book's description

Displaying the activity UI

The application's activity class, MainActivity, inherits directly from the android.app.Activity class. To display the activity's user interface, we override the onCreate method and call the setContentView method passing the R.layout.activity_main layout resource ID.

public class MainActivity extends Activity {
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // load the activity_main layout resource
    setContentView(R.layout.activity_main);
  }

  // Other methods elided for clarity
}

The new thinking – fragment-oriented

The activity-oriented user interface we currently have would be fine if all Android devices had the same form factor. As we've discussed, that's not the case.

We need to partition the application user interface so that we can switch to a fragment-oriented approach. With proper partitioning, we can be ready to make some simple enhancements to our application to help it adapt to device differences.

Let's look at some simple changes we can make that will partition our user interface.

Creating the fragment layout resources

The first step in moving to a fragment-oriented user interface is to identify the natural partitions in the existing user interface. In the case of this application, the natural partitions are reasonably easy to identify. The list of book titles is one good candidate, and the book description is the other. We'll make them each a separate fragment.

Defining the layout as a reusable list

For the list of book titles, we have the option to define the fragment to contain either the ScrollView element that's nearest to the top (has an id value of scrollTitles) or just the RadioGroup element within that ScrollView element. When creating a fragment, we want to structure it such that the fragment is most easily reused. Although the RadioGroup element is all we need to display the list of titles, it seems likely that we'll always want the user to be able to scroll the list of titles if necessary. With this being the case, it makes sense to include the ScrollView element in this fragment.

To create a fragment for the book list, we define a new layout resource file called fragment_book_list.xml. We copy the top ScrollView element and its contents from the activity_main.xml resource file to the fragment_book_list.xml resource file. The resulting fragment_book_list.xml resource file is as follows:

<!-- List of Book Titles -->
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:id="@+id/scrollTitles"
    android:layout_weight="1">
  <RadioGroup
      android:id="@+id/bookSelectGroup "
      android:layout_height="wrap_content"
      android:layout_width="wrap_content" >
    <RadioButton
        android:id="@+id/dynamicUiBook"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="@string/dynamicUiTitle"
        android:checked="true"   />
    <RadioButton
        android:id="@+id/android4NewBook"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="@string/android4NewTitle"    />

    <!-- Other RadioButtons elided for clarify -->

  </RadioGroup>
</ScrollView>

This gives us a layout resource consistent with the book title portion of the user interface as it appeared in the activity layout resource. This is a good start.

Minimize assumptions

An effective fragment-oriented user interface is constructed with layout resources that minimize assumptions about where and how the fragment is used. The fewer assumptions we make about a fragment's use, the more reusable the fragment becomes.

The layout in the fragment_book_list.xml resource file as we now have it is very limiting because it includes significant assumptions. For example, the root ScrollView element includes a layout_height attribute with a value of 0. This assumes that the fragment will be placed within a layout that calculates the height for the fragment.

A layout_height attribute value of 0 prevents the ScrollView element from properly rendering when we use the fragment within any of the many layouts that require the ScrollView element to specify a meaningful height. A layout_height attribute value of 0 prevents the fragment from properly rendering even when doing something as simple as placing the fragment within a horizontally oriented LinearLayout element. The layout_weight attribute has similar issues.

In general, a good practice is to design the fragment to fully occupy whatever space it is placed within. This gives the layout in which the fragment is used the most control over the placement and sizing of the fragment.

To do this, we'll remove the layout_weight attribute from the ScrollView element and change the layout_height attribute value to match_parent. Because the ScrollView element is now the root node of the layout resource, we also need to add the android namespace prefix declaration.

The following code snippet shows the updated ScrollView element:

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/scrollTitles">

  <!—RadioGroup and RadioButton elements elided for clarity -->

</ScrollView>

With the updated ScrollView element, the fragment layout can now adapt to almost any layout it's referenced within.

Encapsulating the display layout

For the book description, we'll define a layout resource file called fragment_book_desc.xml. The fragment layout includes the contents of the activity layout resource's bottom ScrollView element (has an id value of scrollDescription). Just as in the book list fragment, we'll remove the layout_weight attribute, set the layout_height attribute to match_parent, and add the android namespace prefix declaration.

The fragment_book_desc.xml layout resource file appears as follows:

<!-- Description of selected book -->
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/scrollDescription">
  <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textAppearance="?android:attr/textAppearanceMedium"
      android:text="@string/dynamicUiDescription"
      android:id="@+id/textView"
      android:paddingLeft="@dimen/activity_horizontal_margin"
      android:paddingRight="@dimen/activity_horizontal_margin"
      android:gravity="fill_horizontal"/>
</ScrollView>

Creating the Fragment class

Just like when creating an activity, we need more than a simple layout definition for our fragment; we also need a class.

Wrapping the list in a fragment

All fragment classes must extend the android.app.Fragment class either directly or indirectly.

Note

For projects that rely on the Android Support Library to provide fragment support for pre-API Level 11 (Android 3.0) devices, use the android.support.v4.app.Fragment class in place of the android.app.Fragment class.

We'll call the class for the fragment that manages the book list, BookListFragment. The class will directly extend the Fragment class as follows:

Import android.app.Ftragment;
public class BookListFragment extends Fragment { … }

During the creation of a fragment, the Android framework calls a number of methods on that fragment. One of the most important of these is the onCreateView method. The onCreateView method is responsible for returning the view hierarchy represented by the fragment. The Android framework attaches that returned view hierarchy for the fragment to the appropriate place in the activity's overall view hierarchy.

In a case like the BookListFragment class where the Fragment class inherits directly from the Fragment class, we must override the onCreateView method and perform the work necessary to construct the view hierarchy.

The onCreateView method receives three parameters. We'll focus on just the first two for now:

  • inflater: This is a reference to a LayoutInflater instance that is able to read and expand layout resources within the context of the containing activity

  • container: This is a reference to the ViewGroup instance within the activity's layout where the fragment's view hierarchy is to be attached

The LayoutInflater class provides a method called inflate that handles the details of converting a layout resource into the corresponding view hierarchy and returns a reference to the root view of that hierarchy. Using the LayoutInflater.inflate method, we can implement our BookListFragment class' onCreateView method to construct and return the view hierarchy corresponding to the R.layout.fragment_book_list layout resource as shown in the following code:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View viewHierarchy = 
    inflater.inflate(R.layout.fragment_book_list, 
    container, false);
    return viewHierarchy;
}

You'll notice in the preceding code we include the container reference and a Boolean value of false in the call to the inflate method. The container reference provides the necessary layout parameters for the inflate method to properly format the new view hierarchy. The parameter value of false indicates that container is to be used only for the layout parameters. If this value were true, the inflate method would also attach the new view hierarchy to the container view group. We do not want to attach the new view hierarchy to the container view group in the onCreateView method because the activity will handle that.

Providing the display fragment

For the book description fragment, we'll define a class called BookDescFragment. This class is identical to the BookListFragment class except the BookDescFragment class uses the R.layout.fragment_book_desc layout resource as follows:

public class BookDescFragment extends Fragment {
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View viewHierarchy = inflater.inflate(R.layout.fragment_book_desc, container, false);
    return viewHierarchy;
  }
}

Converting the activity to use fragments

With the fragments defined, we can now update the activity to use them. To get started, we'll remove all the book titles and description layout information from the activity_main.xml layout resource file. The file now contains just the top-level LinearLayout element and comments to show where the book titles and description belong as follows:

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

  <!--  List of Book Titles  -->
 
  <!--  Description of selected book  -->

</LinearLayout>

Using the fragment element, we can add a fragment to the layout by referencing the fragment's class name with the name attribute. For example, we reference the book list fragment's class, BookListFragment, as follows:

<fragment
    android:name="com.jwhh.fragments.BookListFragment"
    android:id="@+id/fragmentTitles"/>

We want our activity user interface to appear the same using fragments as it did before we converted it to use fragments. To do this, we add the same layout_width, layout_height, and layout_weight attribute values to the fragment elements as were on the ScrollView elements in the original layout.

With that, the complete layout resource file for the activity, activity_main.xml, now looks like the following code:

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

  <!-- List of Book Titles -->
  <fragment
      android:layout_width="match_parent"
      android:layout_height="0dp"
      android:layout_weight="1"
      android:name="com.jwhh.fragments.BookListFragment"
      android:id="@+id/fragmentTitles"/>

  <!-- Description of selected book -->
  <fragment
      android:layout_width="match_parent"
      android:layout_height="0dp"
      android:layout_weight="1"
      android:name="com.jwhh.fragments.BookDescFragment"
      android:id="@+id/fragmentDescription"/>
</LinearLayout> 

Note

If you are working with Android Studio, you might find a tools:layout attribute on the fragment element. This attribute is used by Android Studio to provide a preview of the layout within the graphical designer. It has no effect on your application's appearance when the application is run.

When the application is run, the user interface will now appear exactly as it did when it was defined entirely within the activity. If we're targeting Android devices running API Level 11 (Android 3.0) or later, there is no need to make any changes to the Activity class because the Activity class is simply loading and displaying the layout resource at this point.

Activities and backward compatibility

When using the Android Support Library to provide pre-API Level 11 (Android 3.0) fragment support, we have one additional step. In this case, we have to make one small, but important change to our activity. We must change the MainActivity class' base class from the Activity class to the android.support.v4.app.FragmentActivity class. Because the pre-API Level 11 Activity class doesn't understand fragments, we use the FragmentActivity class from the Android Support Library to add fragment support to our MainActivity class.

Summary


The shift from the old thinking of being activity-oriented to the new thinking of being fragment-oriented opens our applications up to rich possibilities. Fragments allow us to better organize both the appearance of the user interface and the code we use to manage it. With fragments, our application user interface has a more modular approach that frees us from being tied to the specific capabilities of a small set of devices and prepares us to work with the rich devices of today, and the wide variety of new devices to come tomorrow.

In the next chapter, we'll build on the modularized user interface we've created with fragments to enable our application to automatically adapt to differences in the various device form factors with only minimal changes to our application.

Left arrow icon Right arrow icon

Key benefits

  • Learn everything you need to know to provide dynamic multi-screen UIs within a single activity
  • Integrate the rich UI features demanded by today's mobile users
  • Understand the basics of using fragments and how to use them to create more adaptive and dynamic user experiences

Description

To create a dynamic and multi-pane user interface on Android, you need to encapsulate UI components and activity behaviors into modules that you can swap into and out of your activities. You can create these modules with the fragment class, which behaves somewhat like a nested activity that can define its own layout and manage its own lifecycle. When a fragment specifies its own layout, it can be configured in different combinations with other fragments inside an activity to modify your layout configuration for different screen sizes (a small screen might show one fragment at a time, but a large screen can show two or more). Creating Dynamic UI with Android Fragments shows you how to create modern Android applications that meet the high expectations of today's users. You will learn how to incorporate rich navigation features like swipe-based screen browsing and how to create adaptive UIs that ensure your application looks fantastic whether run on a low cost smartphone or the latest tablet. This book looks at the impact fragments have on Android UI design and their role in both simplifying many common UI challenges and providing new ways to incorporate rich UI behaviors. You will learn how to use fragments to create UIs that automatically adapt to device differences. We look closely at the roll of fragment transactions and how to work with the Android back stack. Leveraging this understanding, we then explore several specialized fragment-related classes like ListFragment and DialogFragment as well as rich navigation features like swipe-based screen browsing.

Who is this book for?

This book is for developers with a basic understanding of Android programming who would like to improve the appearance and usability of their applications. Whether you're looking to create a more interactive user experience, create more dynamically adaptive UIs, provide better support for tablets and smartphones in a single app, reduce the complexity of managing your app UIs, or you are just trying to expand your UI design philosophy, then this book is for you.

What you will learn

  • Understand the role and capabilities of fragments
  • Explore the fragment-oriented features of Android Studio
  • Create an app UI that works effectively on smartphones and tablets
  • Use fragments to create engaging navigation capabilities like swipe-based screen browsing
  • Work with special purpose fragment classes like ListFragment and DialogFragment
  • Dynamically manage fragments using the FragmentTransaction class
  • Learn appropriate application design for communicating between fragments
  • Efficiently handle fragment creation and lifecycle
  • Simplify cross-thread UI handling with fragments
  • Form multi-screen UIs that run within a single activity
Estimated delivery fee Deliver to Czechia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 25, 2013
Length: 122 pages
Edition : 1st
Language : English
ISBN-13 : 9781783283095
Category :
Languages :

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Czechia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Publication date : Sep 25, 2013
Length: 122 pages
Edition : 1st
Language : English
ISBN-13 : 9781783283095
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 111.97
Learning Java by Building Android Games
€36.99
Android NDK Beginner`s Guide - Second Edition
€41.99
Creating Dynamic UI with Android Fragments
€32.99
Total 111.97 Stars icon

Table of Contents

5 Chapters
Fragments and UI Modularization Chevron down icon Chevron up icon
Fragments and UI Flexibility Chevron down icon Chevron up icon
Fragment Lifecycle and Specialization Chevron down icon Chevron up icon
Working with Fragment Transactions Chevron down icon Chevron up icon
Creating Rich Navigation with Fragments Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1
(10 Ratings)
5 star 20%
4 star 70%
3 star 10%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Danny Preussler Nov 29, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The concept of Fragments was introduced in Android Honeycomb. Although this feels like a very long time, it was in fact only 2 years ago. This new book attempts to summarise some of the last 2 years and what we (should) have learned.The book starts with an overview of when to use fragments (and also when not to) and introduces them using an example that we follow throughout the book. The example changes from a simple app into a more advanced one with landscape views, which is later migrated to tablets. This way it changes from a normal layout application into one with fragments.It not only explains resource folders, but also layout aliases mechanism. This is a great start for new developers.If you are already familiar with fragments you might want to skip the first part but should pay attention to the the part about lifecycle. It details exactly how lifecycle and associated methods of activities and fragment are bound. The book describes the important differences between onCreate() and onCreateView() especially when it comes to pausing views and what it means in terms of performance for the developer.The last part of the book covers actionbar navigation examples built with fragments as tabs or dropdown navigation. For me, this is the only negative point in the book -- nowadays most people use menu drawer for navigation, but this is completly missing in the book. It would have been great to see this compared to other modes and what you need to change in your app and how it effects your fragments.Altogether this is an important book. It's not a large book, just a few hundred pages, so a quick read and a quick win.
Amazon Verified review Amazon
Cong La Mar 15, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a one of the best Android books I have had. Good examples and very clear explanations.
Amazon Verified review Amazon
Fabio Radin Dec 09, 2013
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
The book by Jim Wilson is very clear and exhaustive about a powerfull technique of the most modern UI design approach for Android applications. The intention is really clear: to describe with a very detailed level the pros and cons of fragments approach, in contrast with activity based one. In addition to that, Jim explains all the fragments related stuff to create very effective Android UI...Divided in three parts, the first one is a simple but efficient comparison between the traditional way of programming UI for Android and the new one (introduced in Android Honeycomb, 3.0 version, when tablets starts to came out). The middle part covers the lifecycle of fragments inside the Android application (I really appreciate this one!), about two aspects: in the creation, setup, destruction and management of fragments inside the Android application and in the fragment transactions in the UI, in order to create rich UI navigation. In the end, the third part improves the ActionBar design and workflow.The required level to approach this book is more or less low: basic knowledge of Android programming and a working development environment for the examples.In summary, I found this book really helpful to introduce and make you a master in Android Fragment design and code writing.Note: This book was provided for review by Packt.
Amazon Verified review Amazon
Amazon Customer Dec 19, 2013
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Over the past few months I have been trying to expand my knowledge of Android development and this was a great supplement on the subject of Fragments.The in depth coverage of the topics were of a very high standard as I have come to expect of most Packt Publications.This is a must read for any serious Android developer
Amazon Verified review Amazon
Shaju Mathew Dec 03, 2013
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Well presented, succinct, hands-on how-to guide on how to leverage the fragments interface to create a responsive and portable Android UI that behaves as-designed on different form-factors, screen resolutions and operating mode. Unlike other Android/UI material that aspire to be a catch-all for all things ui, this book focuses exclusively on fragments, navigation mechanisms that take advantage of this API, how to promote code reuse and reduce APK footprint. Hard-to-understand concepts such as fragment lifecycle, loosely coupling user-interface segments, dynamic fragment loading, Actionbar integration, swipe navigation in gallery style, implementing tabs with fragments, etc are clearly explained by analyzing the application side-by-side, with and without employing these new functionality exposed by the Android SDK. Obviously, a fundamental understanding of mobile user-interface, Android lifecycle, layouts, are a requirement.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the digital copy I get with my Print order? Chevron down icon Chevron up icon

When you buy any Print edition of our Books, you can redeem (for free) the eBook edition of the Print Book you’ve purchased. This gives you instant access to your book when you make an order via PDF, EPUB or our online Reader experience.

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela