Intro To Android (Workbook 2)

Custom Views

You can create custom views to encapsulate logic much like you can with Fragment's (without all the bother of lifecycle methods).

Types

The simplest way to start is to extend an existing view. For example, let's say you wanted a blinking text-based view. TextView gives you much of what you need to get started, but you just need a little more functionality out of it, so you add it by subclassing the TextView and add background color blinking.

You can also create compound views, which are a collection of views that make sense as a unit. For example, say you wanted to create a card view that had a title, button, description text, and an image. There is no Android control that gives you everything that you need all together, but you could combine them into a new view based off of a ViewGroup (e.g. LinearLayout). You can use XML files as you normally do to create your view and then inflate and configure your new custom view in your class.

Usage

You can include them in an existing XML view by using the fully qualified path:

<com.colabug.views.BlinkingView/>

or in code by instantiating:

BlinkingView blink = new BlinkingView();

In the view class, you inflate the view and configure the view based on data and/or attributes of the view (see below).

Attributes

These views can have their own attributes like the builtin Android components do. You create your own namespace when referencing the view in XML.

In the following example, BlinkingView extends TextView and uses many of the built in features of that view, which are preceded by android: (layout_width, layout_height, textColor, and background). It also allows the user of the view to configure the color that the text should blink by providing a custom attribute, custom:blinkColor.

<com.colabug.views.BlinkingView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res/com.colabug"
    android:id="@+id/cover_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/white"
    android:background="@color/black"
    custom:blinkColor="@color/red"/>