Views
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.