Reader small image

You're reading from  Android 9 Development Cookbook - Third Edition

Product typeBook
Published inOct 2018
Reading LevelIntermediate
PublisherPackt
ISBN-139781788991216
Edition3rd Edition
Languages
Tools
Right arrow
Author (1)
Rick Boyer
Rick Boyer
author image
Rick Boyer

Rick Boyer has been programming professionally for over 20 years. He has written apps on Windows, created websites, and coded for various mobile devices, including Windows CE, Windows Phone, and Android. Almost eight years ago, he took the plunge and started his own software consulting business, NightSky Development, focusing exclusively on Android development.
Read more about Rick Boyer

Right arrow

Chapter 3. Views, Widgets, and Styles

In this chapter, we will cover the following topics:

  • Inserting a widget into a layout
  • Using graphics to show the button state
  • Creating a widget at runtime
  • Creating a custom component
  • Applying a style to a View
  • Turning a style into a theme
  • Selecting a theme based on the Android OS version

Introduction


The term widgets can refer to several different concepts in Android. When most people talk about widgets, they are referring to app widgets, which are typically seen on the home screen. App widgets are like mini applications by themselves as they usually provide a subset of functionality, based on their main application. (Usually, most app widgets are installed along with an application, but that is not a requirement. They can be standalone apps in a widget format.) A common app widget example is a weather application that offers several different app widgets for the home screen. Chapter 6, Beyond Your App - Home Screen Widgets, Search, and the System UI, will discuss home screen app widgets and provide recipes to create your own.

When developing for Android, the term widgets generally refers to specialized Views placed in the layout files, such as a Button, TextView, CheckBox, and so on. This chapter will focus on widgets for screen layouts.

To see the list of widgets provided...

Inserting a widget into a layout


As you may have seen from previous recipes, widgets are declared in a layout file, or created in code. For this recipe, we will go step by step to add a button with the Android Studio Designer. (For later recipes, we will just show the layout XML.) After creating the button, we will create a method to receive the button click events using onClickListener().

Getting ready

Start a new project in Android Studio and call it InsertWidget. Use the default options for creating a Phone and Tablet project and select Empty Activity when prompted for the Activity Type. You can delete the default TextView (or leave it) as it will not be needed for this recipe.

How to do it...

To insert a widget into a layout, follow these steps:

  1. Open the activity_main.xml file in Android Studio and click on the Design tab. As you can see, by default, Android Studio adds a TextView to the layout. Select the TextView and delete it:

  1. Find Button in the widget list and drag it to the center of...

Using graphics to show button state


We've talked about the versatility of Android Views and how behavior and visual appearance can be customized. In this recipe, we will create a drawable state selector, which is a resource defined in XML that specifies the drawable to use based on the View's state. The most commonly used states, along with the possible values, include the following:

  • state_pressed=["true" | "false"]
  • state_focused=["true" | "false"]
  • state_selected=["true" | "false"]
  • state_checked=["true" | "false"]
  • state_enabled=["true" | "false"]

To define a state selector, create an XML file with the <selector> element, as shown:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android" > 
</selector> 

Within the <selector> element, we define an <item> element to identify the drawable to be used based on the specified state(s). Here's an example <item> element using multiple states:

 <item 
    android...

Creating a widget at runtime


As mentioned before, generally, the UI is declared in XML files and then modified during runtime through the Java code. It is possible to create the UI completely in Java code, though for a complex layout, it would generally not be considered best practice.

In this recipe, we are going to add a view to the existing layout defined in activity_main.xml.

Getting ready

Create a new project in Android Studio and call it RuntimeWidget. Select the Empty Activity option when prompted for the Activity Type.

How to do it...

We will start by adding an ID attribute to the existing layout so we can access the layout in code. Once we have a reference to the layout in code, we can add new views to the existing layout. Here are the steps:

  1. Openres/layout/activity_main.xml and add an ID attribute to the root ConstraintLayout, as follows:
android:id="@+id/layout" 
  1. Completely remove the default <TextView> element.
  2. Open the MainActivity.java file so we can add code to the onCreate(...

Creating a custom component


As we have seen in previous recipes, the Android SDK provides a wide range of components. But what happens when you can't find a prebuilt component that fits your unique needs? You can always create your own!

In this recipe, we will walk through creating a custom component that derives from the View class, just like the built-in widgets. Here's a high-level overview:

  1. Create a new class that extends View.
  2. Create custom constructor(s).
  3. Override onMeasure(), as the default implementation returns a size of 100 x 100.
  4. Override onDraw(), as the default implementation draws nothing.
  5. Define custom methods and listeners (such as the onClick() event).
  6. Implement custom functionality.

Note

Overriding onMeasure() and onDraw() is not strictly required, but the default behavior is likely not what you would want.

Getting ready

Start a new project in Android Studio and call it CustomView. Use the default wizard options, including the Phone & Tablet SDK and select Empty Activity when...

Applying a style to a View


A style is a collection of property settings to define the look of a View. As you have already seen while defining layouts, a view offers many settings to determine how it looks, as well as functions. We have already set a view height, width, background color, and padding, plus there are many more settings such as text color, font, text size, margin, and so on. Creating a style is as simple as pulling these settings from the layout and putting them in a style resource.

In this recipe, we will go through the steps of creating a style and hooking it up to a view.

Similar to Cascading Style Sheets, Android Styles allow you to specify your design settings separate from the UI code.

Getting ready

Create a new Android Studio project and call it Styles. Use the default wizard options to create a Phone & Tablet project and select Empty Activity when prompted for the Activity type. We haven't looked at it before, but by default, the wizard also creates a styles.xml file...

Turning a style into a theme


A theme is a style applied to an activity or the whole application. To set a theme, use the android:theme attribute in the AndroidManifest.xml file. The theme attribute applies to the <Application> element as well as the <Activity> elements. All views within that element will be styled with the theme specified.

It's common to set the application theme, but then override a specific activity with a different theme.

In the previous recipe, we set textViewStyle using the AppTheme style (which the wizard created automatically). In this recipe, you will learn how to set both the application and activity themes.

Along with the style settings we have already explored, there are additional style options we didn't discuss because they don't apply to a View, they apply to the window as a whole. Settings such as hiding the application title or action bar and setting the window background, just to name a few, apply to the window and therefore must be set as a theme...

Selecting a theme based on the Android version


Most users prefer to see apps using the latest themes provided by Android. To be competitive with the many other apps in the market, you'll probably want to upgrade your app as well, but what about your users who are still running older versions of Android? By setting up our resources properly, we can use resource selection in Android to automatically define the parent theme based on the Android OS version the user is running.

First, let's explore the three main themes available in Android:

  • Theme - Gingerbread and earlier
  • Theme.Holo - Honeycomb (API 11)
  • Theme.Material - Lollipop (API 21)

This recipe will show how to properly set up the resource directories for Android to use the most appropriate theme based on the API version the app is running on.

Getting ready

Start a new project in Android Studio and call it AutomaticThemeSelector. Use the default wizard option to make a Phone & Tablet project. Select the Empty Activity when prompted for the...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android 9 Development Cookbook - Third Edition
Published in: Oct 2018Publisher: PacktISBN-13: 9781788991216
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Rick Boyer

Rick Boyer has been programming professionally for over 20 years. He has written apps on Windows, created websites, and coded for various mobile devices, including Windows CE, Windows Phone, and Android. Almost eight years ago, he took the plunge and started his own software consulting business, NightSky Development, focusing exclusively on Android development.
Read more about Rick Boyer