Home > Articles

Views

In this chapter from Android Development Patterns, Phil Dutson covers the View class and several subclasses, and explains how to create a custom view.
This chapter is from the book

Of all the pieces of the Android system, views are probably the most used. Views are the core building block on which almost every piece of the UI is built. They are versatile and, as such, are used as the foundation for widgets. In this chapter, you learn how to use and how to create your own view.

The View Class

A view is a rather generic term for just about anything that is used in the UI and that has a specific task. Adding something as simple as a button is adding a view. Some widgets, including Button, TextView, and EditText widgets, are all different views.

Looking at the following line of code, it should stand out that a button is a view:

Button btnSend = (Button) findViewById(R.id.button);

You can see that the Button object is defined and then set to a view defined in the application layout XML file. The findViewById() method is used to locate the exact view that is being used as a view. This snippet is looking for a view that has been given an id of button. The following shows the element from the layout XML where the button was created:

<Button
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="@string/button_text"
  android:id="@+id/button"
  android:layout_below="@+id/textView"
  android:layout_centerHorizontal="true" />

Even though the element in the XML is <Button>, it is still considered a view. This is because Button is what is called an indirect subclass of View. In total, there are more than 80 indirect subclasses of View as of API level 21. There are 11 direct subclasses of View: AnalogClock, ImageView, KeyboardView, MediaRouteButton, ProgressBar, Space, SurfaceView, TextView, TextureView, ViewGroup, and ViewStub.

The AnalogClock Subclass

The AnalogClock is a complex view that shows an analog clock with a minute-hand and an hour-hand to display the current time.

Adding this view to your layout XML is done with the following element:

<AnalogClock
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:id="@+id/analogClock"
  android:layout_centerVertical="true"
  android:layout_centerHorizontal="true" />

This view can be attached to a surface by using the onDraw(Canvas canvas) method, and it can be sized to scale to the screen it is being displayed on via the following method:

onMeasure(int widthMeasureSpec, int heightMeasureSpec)

It should be noted that if you decide to override the onMeasure() method, you must call setMeasuredDimension(int, int). Otherwise, an IllegalStateException error will be thrown.

The ImageView Subclass

The ImageView is a handy view that can be used to display images. It is smart enough to do some simple math to figure out dimensions of the image it is displaying, which in turn allows it to be used with any layout manager. It also allows for color adjustments and scaling the image.

Adding an ImageView to your layout XML requires the following:

<ImageView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:id="@+id/imageView"
  android:src="@drawable/car"
  android:layout_centerVertical="true"
  android:layout_centerHorizontal="true" />

To show multiple figures, you can use multiple ImageViews within a layout. Similar to other views, you can attach events such as a click event to trigger other behavior. Depending on the application you are building, this may be advantageous versus requiring the user to click a button or use another widget to complete an action.

The KeyboardView Subclass

The KeyboardView is one of the most interesting views that exist. This is one of the true double-edged components of the Android system. Using the KeyboardView allows you to create your own keyboard. Several keyboards exist in the Play store that you can download right now and use on your Android device that are based on using the KeyboardView.

The problem is that using an application with a custom keyboard means that all data entry must pass through it. Every “keystroke” is passed through the application, and that alone tends to send shivers down the spine of those who are security conscious. However, if you are an enterprise developer and need a custom keyboard to help with data entry, then this view may be exactly what you are looking for.

Creating your own keyboard is an involved process. You need to do the following:

  • Create a service in your application manifest.
  • Create a class for the keyboard service.
  • Add an XML file for the keyboard.
  • Edit your strings.xml file.
  • Create the keyboard layout XML file.
  • Create a preview TextView.
  • Create your keyboard layout and assign values.

The KeyboardView has several methods you can override to add functionality to your keyboard:

  • onKey()
  • onPress()
  • onRelease()
  • onText()
  • swipeDown()
  • swipeUp()
  • swipeLeft()
  • swipeRight()

You do not need to override all of these methods; you may find that you only need to use the onKey() method.

The MediaRouteButton Subclass

The MediaRouteButton that is part of the compatibility library is generally used when working with the Cast API. This is where you need to redirect media to a wireless display or ChromeCast device. This view is the button that is used to allow the user to select where to send the media.

Note that per Cast design guidelines, the button must be considered “top level.” This means that you can create the button as part of the menu or as part of the ActionBar. After you create the button, you must also use the .setRouteSelector() method; otherwise, an exception will be thrown.

First, you need to add an <item> to your menu XML file. The following is a sample <item> inside of the <menu> element:

<item
android:id="@+id/mediaroutebutton_cast"
android:actionProviderClass="android.support.v7.app.MediaRouteActionProvider"
android:actionViewClass="android.support.v7.app.MediaRouteButton"
android:showAsAction="always"
android:visible="false"
android:title="@string/mediaroutebutton"/>

Now that you have a menu item created, you need to open your MainActivity class and use the following import:

import android.support.v7.app.MediaRouteButton;

Next, you need to declare it in your MainActivity class:

private MediaRouteButton myMediaRouteButton;

Finally, add the code for the MediaRouteButton to the menu of the onCreateOptionsMenu() method. Remember that you must also use setRouteSelector() on the MediaRouteButton. The following demonstrates how this is accomplished:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
  super.onCreateOptionsMenu(menu);
  getMenuInflater().inflate(R.menu.main, menu);

  myMediaRouteItem = menu.findItem(R.id.mediaroutebutton_cast);
  myMediaRouteButton = (MediaRouteButton) myMediaRouteItem.getActionView();
  myMediaRouteButton.setRouteSelector(myMediaRouteSelector);
  return true;
}

The ProgressBar Subclass

The progress bar is a familiar UI element. It is used to indicate that something is happening and how far along this process is. It is not always possible to determine how long an action will take; luckily, the ProgressBar can be used in indeterminate mode. This allows an animated circle to appear that shows movement without giving a precise measurement of the status of the load.

To add a ProgressBar, you need to add the view to your layout XML. The following shows adding a “normal” ProgressBar:

<ProgressBar
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:id="@+id/progressBar"
  android:layout_centerVertical="true"
  android:layout_centerHorizontal="true" />

Other styles of ProgressBar may also be used. To change the style, you need to add a property to the <ProgressBar> element. The following styles may be used:

Widget.ProgressBar.Horizontal
Widget.ProgressBar.Small
Widget.ProgressBar.Large
Widget.ProgressBar.Inverse
Widget.ProgressBar.Small.Inverse
Widget.ProgressBar.Large.Inverse

Depending on your implementation, you may apply the style either with your styles.xml or from your attrs.xml. For the styles from styles.xml, you would use the following:

style="@android:style/Widget.ProgressBar.Small"

If you have styles inside your attrs.xml file that you want applied to the progress bar, use the following property in the <ProgressBar> element:

style="?android:attr/progressBarStyleSmall"

If you are planning on using the indeterminate mode, you need to pass a property of android:indeterminate into the <ProgressBar> element. You may also specify the loading animation by setting the android:indeterminateDrawable to a resource of your choosing.

A ProgressBar that is determinate requires updates to be passed to it via the setProgress() or incrementProgressBy() method. These methods should be called from a worker thread. The following shows an example of a thread that uses a Handler and an int for keeping the progress value, and a ProgressBar has been initialized:

new Thread(new Runnable() {
  public void run() {
    while (myProgress < 100) {
      myProgress = doWork();
      myHandler.post(new Runnable() {
        public void run() {
          myProgressBar.setProgress(myProgress);
        }
      });
    }
  }
}).start();

The Space Subclass

For those who have worked on layouts and visual interfaces, the Space view is one that is both helpful and brings on somewhat lucid nightmares. This view is reserved to add “space” between other views and layout objects.

The benefit to using a Space is that it is a --lightweight view that can be easily inserted and modified to fit your needs without you having to do an absolute layout or extra work trying to figure out how relative spacing would work on complex layouts.

Adding a Space is done by adding the following to your layout XML:

<Space
  android:layout_width="1dp"
  android:layout_height="40dp" />

The SurfaceView Subclass

The SurfaceView is used when rendering visuals to the screen. This may be as complex as providing a playback surface for a live camera feed, or it can be used for rendering images on a transparent surface.

The SurfaceView has two major callbacks that act as lifecycle mechanisms that you can use to your advantage: SurfaceHolder.Callback.surfaceCreated() and SurfaceHolder.Callback.surfaceDestroyed(). The time in between these methods is where any work with drawing on the surface should take place. Failing to do so may cause your application to crash and will get your animation threads out of sync.

Adding a SurfaceView requires adding the following to your layout XML:

<SurfaceView
  android:id="@+id/surfaceView"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:layout_weight="1" />

Depending on how you are going to use your SurfaceView, you may want to use the following callback methods:

  • surfaceChanged()
  • surfaceCreated()
  • surfaceDestroyed()

Each of these callback methods gives you an opportunity to initialize values, change them, and more importantly free some system resources up when it is released. If you are using a SurfaceView for rendering video from the device camera, it is essential that you release control of the camera during the surfaceDestroyed() method. Failing to release the camera will throw errors when you attempt to resume usage of the camera in either another application or when your application is resumed. This is due to a new instance attempting to open on a resource that is finite and currently marked as in use.

The TextView Subclass

The TextView is likely the first view added to your project. If you create a new project in Android Studio that follows the default options, you will be given a project that contains a TextView with a string value of “Hello World” in it.

To add a TextView, you need to add the following code to your layout XML file:

<TextView
  android:text="@string/hello_world"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" />

Note that in the previous example, the value for the TextView is taken from @string/hello_world. This value is inside of the strings.xml file that is in your res/values folder for your project. The value is defined in strings.xml as follows:

<string name="hello_world">Hello world!</string>

The TextView also contains a large number of options that can be used to help format, adjust, and display text in your application. For a full list of properties, visit http://developer.android.com/reference/android/widget/TextView.html.

The TextureView Subclass

The TextureView is similar to the SurfaceView but carries the distinction of being tied directly to hardware acceleration. OpenGL and video can be rendered to the TextureView, but if hardware acceleration is not used for the rendering, nothing will be displayed. Another difference when compared to SurfaceView is that TextureView can be treated like a View. This allows you to set various properties including setting transparency.

In similarity to SurfaceView, some methods need to be used with TextureView in order for proper functionality. You should first create your TextureView and then use either getSurfaceTexture() or TextureView.SurfaceTextureListener before using setContentView().

Callback methods should also be used for logic handling while working with the TextureView. Paramount among these callback methods is the onSurfaceTextureAvailable() method. Due to TextureView only allowing one content provider to manipulate it at a time, the onSurfaceTextureAvailable() method can allow you to handle IO exceptions and to make sure you actually have access to write to it.

The onSurfaceTextureDestroyed() method should also be used to release the content provider to prevent application and resource crashing.

The ViewGroup Subclass

The ViewGroup is a special view that is used for combining multiple views into a layout. This is useful for creating unique and custom layouts. These views are also called “compound views” and, although they are flexible, they may degrade performance and render poorly based on the number of children included, as well as the amount of processing that needs to be done for layout parameters.

CardView

The CardView is part of the ViewGroup that was introduced in Lollipop as part of the v7 support library. This view uses the Material design interface to display views on “cards.” This is a nice view for displaying compact information in a native Material style. To use the CardView, you can load the support library and wrap your view elements in it. The following demonstrates an example:

<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:paddingLeft="@dimen/activity_horizontal_margin"
  android:paddingRight="@dimen/activity_horizontal_margin"
  android:paddingTop="@dimen/activity_vertical_margin"
  android:paddingBottom="@dimen/activity_vertical_margin"
  tools:context=".MainActivity">

  <android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_gravity="center"
    android:layout_width="200dp"
    android:layout_height="200dp"
    card_view:cardCornerRadius="4dp"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true">

  <TextView android:text="@string/hello_world"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
  </android.support.v7.widget.CardView>
</RelativeLayout>

This example shows a card in the center of the screen. The color and corner radius can be changed via attributes in the <android.support.v7.widget.CardView> element. Using card_view:cardBackgroundColor will allow you to change the background color, and using card_view:cardCornerRadius will allow you to change the corner radius value.

RecyclerView

The RecyclerView was also added in Lollipop as part of the v7 support library. This view is a replacement for the aging ListView. It brings with it the ability to use a LinearLayoutManager, StaggeredLayoutManager, and GridLayoutManager as well as animation and decoration support. The following shows how you can add this view to your layout XML:

<android.support.v7.widget.RecyclerView
    android:id="@+id/my_recycler_view"
    android:scrollbars="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Similar to with a ListView, after you have added the RecyclerView to your layout, you then need to instantiate it, connect it to a layout manager, and then set up an adapter to display data.

You instantiate the RecyclerView by setting it up as follows:

myRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

The following shows connecting to a layout manager using the LinearLayoutManager that is part of the v7 support library:

myLayoutManager = new LinearLayoutManager(this);
myRecyclerView.setLayoutManager(myLayoutManager);

All that is left is to attach the data from an adapter to the RecyclerView. The following demonstrates how this is accomplished:

myAdapter = new MyAdapter(myDataset);
myRecyclerView.setAdapter(myAdapter);

The ViewStub Subclass

The ViewStub is a special view that is used to create views on demand in a reserved space. The ViewStub is placed in a layout where you want to place a view or other layout elements at a later time. When the ViewStub is displayed—either by setting its visibility with setVisibility(View.VISIBLE) or by using the inflate() method—it is removed and the layout it specifies is then injected into the page.

The following shows the XML needed to include a ViewStub in your layout XML file:

<ViewStub
    android:id="@+id/stub"
    android:inflatedId="@+id/panel_import"
    android:layout="@layout/progress_overlay"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom" />

When the ViewStub is inflated, it will use the layout specified by the android:layout property. The newly inflated view will then be accessible via code by the ID specified by the android:inflatedId property.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020