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
Android Application Development Cookbook
Android Application Development Cookbook

Android Application Development Cookbook: Over 100 recipes to help you solve the most common problems faced by Android Developers today , Second Edition

eBook
$35.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
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

Billing Address

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

Android Application Development Cookbook

Chapter 2. Layouts

In this chapter, we will cover the following topics:

  • Defining and inflating a layout
  • Using RelativeLayout
  • Using LinearLayout
  • Creating tables – TableLayout and GridLayout
  • Using ListView, GridView, and Adapters
  • Changing layout properties during runtime
  • Optimizing layouts with the Hierarchy Viewer

Introduction

In Android, the User Interface is defined in a Layout. A layout can be declared in XML or created dynamically in code. (It's recommended to declare the layout in XML rather than in code to keep the presentation layer separate from the implementation layer.) A layout can define an individual ListItem, a fragment, or even the entire Activity. Layout files are stored in the /res/layout folder and referenced in code with the following identifier: R.layout.<filename_without_extension>.

Android provides a useful variety of Layout classes that contain and organize individual elements of an activity (such as buttons, checkboxes, and other Views). The ViewGroup object is a container object that serves as the base class for Android's family of Layout classes. The Views placed in a layout form a hierarchy, with the topmost layout being the parent.

Android provides several built-in layout types designed for specific purposes, such as the RelativeLayout, which allows Views...

Defining and inflating a layout

When using the Android Studio wizard to create a new project, it automatically creates the res/layout/activity_main.xml file (as shown in the following screenshot). It then inflates the XML file in the onCreate() callback with setContentView(R.layout.activity_main).

Defining and inflating a layout

For this recipe, we will create two, slightly different layouts and switch between them with a button.

Getting ready

Create a new project in Android Studio and call it InflateLayout. Once the project is created, expand the res/layout folder so we can edit the activity_main.xml file.

How to do it...

  1. Edit the res/layout/activity_main.xml file so it includes a button as defined here:
    <Button
        android:id="@+id/buttonLeft"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Left Button"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:onClick=&quot...

Using RelativeLayout

As mentioned in the Introduction, the RelativeLayout allows Views to be position-relative to each other and the parent. RelativeLayout is particularly useful for reducing the number of nested layouts, which is very important for reducing memory and processing requirements.

Getting ready

Create a new project and call it RelativeLayout. The default layout uses a RelativeLayout, which we will use to align Views both horizontally and vertically.

How to do it...

  1. Open the res/layout/activity_main.xml file and change it as follows:
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Centered"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content...

Using LinearLayout

Another common layout option is the LinearLayout, which arranges the child Views in a single column or single row, depending on the orientation specified. The default orientation (if not specified) is vertical, which aligns the Views in a single column.

The LinearLayout has a key feature not offered in the RelativeLayout—the weight attribute. We can specify a layout_weight parameter when defining a View to allow the View to dynamically size based on the available space. Options include having a View fill all the remaining space (if a View has a higher weight), having multiple Views fit within the given space (if all have the same weight), or spacing the Views proportionally by their weight.

We will create a LinearLayout with three EditText Views to demonstrate how the weight attribute can be used. For this example, we will use three EditText Views—one to enter a To Address parameter, another to enter a Subject, and the third to enter a Message. The To and...

Creating tables – TableLayout and GridLayout

When you need to create a table in your UI, Android provides two convenient layout options: the TableLayout (along with TableRow) and the GridLayout (added in API 14). Both layout options can create similar looking tables, but each using a different approach. With the TableLayout, rows and columns are added dynamically as you build the table. With the GridLayout, row and column sizes are defined in the layout definition.

Neither layout is better, it's just a matter of using the best layout for your needs. We'll create a 3 x 3 grid using each layout to give a comparison, as you could easily find yourself using both layouts, even within the same application.

Getting ready

To stay focused on the layouts and offer an easier comparison, we will create two separate applications for this recipe. Create two new Android projects, the first called TableLayout and the other called GridLayout.

How to do it...

  1. Starting with the TableLayout project...

Using ListView, GridView, and Adapters

The ListView and GridView are both descendants of ViewGroup, but they are used more like a View since they are data driven. In other words, rather than defining all the possible Views that might fill a ListView (or GridView) at design time, the contents are created dynamically from the data passed to the View. (The layout of the ListItem might be created at design time to control the look of the data during runtime.)

As an example, if you needed to present a list of countries to a user, you could create a LinearLayout and add a button for each country. There are several problems with this approach: determining the countries available, keeping the list of buttons up to date, having enough screen space to fit all the countries, and so on. Otherwise, you could create a list of countries to populate a ListView, which will then create a button for each entry.

We will create an example, using the second approach, to populate a ListView from an array of country...

Introduction


In Android, the User Interface is defined in a Layout. A layout can be declared in XML or created dynamically in code. (It's recommended to declare the layout in XML rather than in code to keep the presentation layer separate from the implementation layer.) A layout can define an individual ListItem, a fragment, or even the entire Activity. Layout files are stored in the /res/layout folder and referenced in code with the following identifier: R.layout.<filename_without_extension>.

Android provides a useful variety of Layout classes that contain and organize individual elements of an activity (such as buttons, checkboxes, and other Views). The ViewGroup object is a container object that serves as the base class for Android's family of Layout classes. The Views placed in a layout form a hierarchy, with the topmost layout being the parent.

Android provides several built-in layout types designed for specific purposes, such as the RelativeLayout, which allows Views to be positioned...

Defining and inflating a layout


When using the Android Studio wizard to create a new project, it automatically creates the res/layout/activity_main.xml file (as shown in the following screenshot). It then inflates the XML file in the onCreate() callback with setContentView(R.layout.activity_main).

For this recipe, we will create two, slightly different layouts and switch between them with a button.

Getting ready

Create a new project in Android Studio and call it InflateLayout. Once the project is created, expand the res/layout folder so we can edit the activity_main.xml file.

How to do it...

  1. Edit the res/layout/activity_main.xml file so it includes a button as defined here:

    <Button
        android:id="@+id/buttonLeft"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Left Button"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:onClick="onClickLeft"/>
  2. Now make a copy of activity_main.xml and call it...

Left arrow icon Right arrow icon

Key benefits

  • Find the answers to your common Android programming problems, from set up to security, to help you deliver better applications, faster
  • Uncover the latest features of Android Marshmallow to make your applications stand out
  • Get up to speed with Android Studio 1.4 - the first Android Studio based on the IntelliJ IDE from JetBrains

Description

The Android OS has the largest installation base of any operating system in the world; there has never been a better time to learn Android development to write your own applications, or to make your own contributions to the open source community! This “cookbook” will make it easy for you to jump to a topic of interest and get what you need to implement the feature in your own application. If you are new to Android and learn best by “doing,” then this book will provide many topics of interest. Starting with the basics of Android development, we move on to more advanced concepts, and we’ll guide you through common tasks developers struggle to solve. The first few chapters cover the basics including Activities, Layouts, Widgets, and the Menu. From there, we cover fragments and data storage (including SQLite), device sensors, the camera, and GPS. Then we move on more advanced topics such as graphics and animation (including OpenGL), multi-threading with AsyncTask, and Internet functionality with Volley. We’ll also demonstrate Google Maps and Google Cloud Messaging (also known as Push Notifications) using the Google API Library. Finally, we’ll take a look at several online services designed especially for Android development. Take your application big-time with full Internet web services without having to become a server admin by leveraging the power of Backend as a Service (BaaS) providers.

Who is this book for?

If you are new to Android development and want to take a hands-on approach to learning the framework, or if you are an experienced developer in need of clear working code to solve the many challenges in Android development, you can benefit from this book. Either way, this is a resource you’ll want to keep at your desk for a quick reference to solve new problems as you tackle more challenging projects.

What you will learn

  • Along with Marshmallow, get hands-on working with Google's new Android Studio IDE
  • Develop applications using the latest Android framework while maintaining backward-compatibility with the support library
  • Master Android programming best practices from the recipes
  • Create exciting and engaging applications using knowledge gained from recipes on graphics, animations, and multimedia
  • Work through succinct steps on specifics that will help you complete your project faster
  • Keep your app responsive (and prevent ANRs) with examples on the AsynchTask class
  • Utilize Google Speech Recognition APIs for your app.
  • Make use of Google Cloud Messaging (GCM) to create Push Notifications for your users
  • Get a better understanding of the Android framework through detailed explanations

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 31, 2016
Length: 428 pages
Edition : 2nd
Language : English
ISBN-13 : 9781785889202
Vendor :
Google
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
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

Billing Address

Product Details

Publication date : Mar 31, 2016
Length: 428 pages
Edition : 2nd
Language : English
ISBN-13 : 9781785889202
Vendor :
Google
Category :
Languages :
Tools :

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 $ 142.97
Android Application Development Cookbook
$48.99
Learning Material Design
$38.99
Android Programming for Beginners
$54.99
Total $ 142.97 Stars icon

Table of Contents

16 Chapters
1. Activities Chevron down icon Chevron up icon
2. Layouts Chevron down icon Chevron up icon
3. Views, Widgets, and Styles Chevron down icon Chevron up icon
4. Menus Chevron down icon Chevron up icon
5. Exploring Fragments, AppWidgets, and the System UI Chevron down icon Chevron up icon
6. Working with Data Chevron down icon Chevron up icon
7. Alerts and Notifications Chevron down icon Chevron up icon
8. Using the Touchscreen and Sensors Chevron down icon Chevron up icon
9. Graphics and Animation Chevron down icon Chevron up icon
10. A First Look at OpenGL ES Chevron down icon Chevron up icon
11. Multimedia Chevron down icon Chevron up icon
12. Telephony, Networks, and the Web Chevron down icon Chevron up icon
13. Getting Location and Using Geofencing Chevron down icon Chevron up icon
14. Getting your app ready for the Play Store Chevron down icon Chevron up icon
15. The Backend as a Service Options Chevron down icon Chevron up icon
Index 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.5
(6 Ratings)
5 star 66.7%
4 star 16.7%
3 star 16.7%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Amazon Customer Feb 10, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Overall, I really like this book.The recipes are very concise and easy to follow.Only one drawback is, some recipes are not available for API 23+ because of Google's new policies.In that kind of case, I would like to recommend using API 22 or lower emulator or device.
Amazon Verified review Amazon
Hugo May 15, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is a must have if you are an Android developer or want to be, the author's have covered almost everything from the basic/intermediate/advanced level topics in an Android app and split all this content in recipes as the title of the book already suggest this is a true cookbook, I think that real examples better learning for me, than just read the documentation, this book have a great structure and the examples are totally expandable, so you can adapt to your own projects and be able to produce any kind of application you want to and speed your learning process. The recipes are very rich on each topic of application development covering examples of activities, layouts, network, multimedia, data, back end services, graphics, Play Store API's, geofencing and much more. Both of the authors have a great background on Android development and I have to say that the book is very good to help every Android developer.
Amazon Verified review Amazon
Amazon Customer Jan 11, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
GREAT Android development book! A rare combination of an easy to understand programming book that is also comprehensive in its coverage of Android app development. What I really like about the Android Application Development Cookbook is that it not only shows you the code for each cookbook recipe but then it goes through the code examples and explains exactly what each line does.Great way to learn Android/Java while creating usable programs. Outstanding!
Amazon Verified review Amazon
Emil Atanasov May 12, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
[Disclosure]I'm one of the technical reviewers of this book. The book covers all the basics of Android development and a few advanced topics which every developer faces when starting developing mobile applications. Each chapter discusses different parts of the framework in detail. It presents short recipes, how to solve common problems by introducing different parts of the Android framework. By combining most recipes in the end you will be able to write pretty complex applications. Those apps will incorporate different views, displaying data, geo-locations, checking for permissions, fetching data from servers and you will be able to integrate 3rd party services.The book is a comprehensive list of recipes, each one - explains step by step a solution of a common problem. The explanation is supported with code example(s) and screen shots, which guide you through the process of implementation.Different chapters discuss most important topics like - layouts and views, fragments and menus, working with data - local and external, also presenting media and how to upload a final .apk to the play store and how to use third party services.My favorite feature parts of the book are the pieces where the implementation is compliant with the new Android Marshmallow.
Amazon Verified review Amazon
Creosote Apr 29, 2017
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
A nice, lead-by-example book. More software books should take this approach.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.