Android Custom View Tutorial
Create an Android Custom View in Kotlin and learn how to draw shapes on the canvas, make views responsive, create new XML attributes, and save view state. By Ahmed Tarek.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Android Custom View Tutorial
25 mins
- Getting Started
- Working with the Basic Widgets
- Working with Views in Kotlin
- Working with Views in XML
- Android Views
- Custom View and Custom ViewGroup
- How Android Draws Views
- Creating a custom view
- Android View Class Constructors
- Drawing on Canvas
- Responsive View
- Creating Custom XML Attributes
- User Interaction
- Saving View State
- Where To Go From Here?
- Innovative UI design or animation
- Different user interaction
- Displaying different types of data
- Some performance optimization
- Reusability
In this tutorial, you will get a head start with Android custom views by learning how to make an emotional face view that can be set to happy or sad according to your user state, and through that you will see how to add new XML
attributes to a custom view and how to draw some shapes and paths on the Android Canvas
.
If you’re completely new to Android, you might want to first check out Beginning Android Development Part One.
To follow along with this tutorial, you’ll need to use Android Studio 3.0.1 or later and Kotlin 1.2.21 or later.
Getting Started
To kick things off, start by downloading the materials for this tutorial (you can find a link at the top or bottom of the page) and then fire up Android Studio and import the starter project. It is (mostly) an empty project with some resources (colors, dimens and icon launcher).
Build and run the app, and you will see an empty screen like this:
Working with the Basic Widgets
Android has a set of basic widgets and the base class of any Android widget is the View
class.
The following image shows a part of the basic widget hierarchy:
You have two ways to create a new instance of an Android view and to set values for its attributes:
- From your XML files (layout files)
- From your Kotlin code
Working with Views in Kotlin
You can add a TextView
to your layout from the Kotlin code. Open MainActivity and replace the setContentView(R.layout.activity_main)
line in onCreate()
with the following code:
// 1
val textView = TextView(this)
// 2
textView.text = "Hello Custom Views"
// 3
setContentView(textView)
Here, you:
- Create a TextView by using the constructor which needs the activity context.
- Set “Hello Custom Views” as the text of the
TextView
. - Set the
TextView
as the content view of the activity.
Build and run. You will see the text “Hello Custom Views” on your screen like this:
Working with Views in XML
Now open up res/layout/activity_main.xml. To use one of the basic Android widgets like TextView
, just drag it from the palette window on the left into the design editor and drop it to the top center of the layout, or switch to the XML text editor and add the following lines to the XML code inside the RelativeLayout
:
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Hello Custom Views"/>
You can change a lot of basic attributes from the View
class in XML, such as id, layout_width, layout_height, alpha, visibility, elevation, padding, tag
, etc.
To change an attribute, like the text
of a TextView, just add the attribute name (android:text
) and assign a value to it ("Hello Custom Views"
), as in the last line of the previous snippet.
Reset onCreate()
in MainActivity to use setContentView(R.layout.activity_main)
, and remove the code you added earlier. Build and run the project. You will see the text "Hello Custom Views"
on your screen, like this:
Android Views
The Android View class is the basic building block of an Android user interface. A View occupies a rectangular area on the screen to draw itself and its children (for the case of a ViewGroup). Also, a View is responsible for user event handling.
ViewGroup is a subclass of the View
class. ViewGroup is the base class for Android layouts, which are containers for a set of Views (or other ViewGroups), and define their own layout properties and also where each subview should draw itself.
Custom View and Custom ViewGroup
What is a custom View?
Sometimes you want to show a certain type of data and there is already a suitable view in the basic widget set. But if you want UI customization or a different user interaction, you may need to extend a widget.
Suppose that there were no Button widget in the basic widget set in the Android SDK and you want to make one. You would extend the TextView
class to get all the capabilities related to the text like setting text, text color, text size, text style and so on. Then you will start your customization work, to give your new widget the look and feel of a button. this is what happens in the Android SDK the Button class extends the TextView
class.
Or you could in theory extend the View class to start from scratch.
What is a custom ViewGroup?
Sometimes you want to group some views into one component to allow them to deal with each other easily through writing some specific code or business logic. You can call that a “compound view”. Compound views give you reusability and modularity.
For example, you may want to build an emotional face view with a sliding bar that the user can slide to the right to make the emotional face happier or slide to left to make it sadder. You may also want to show that state of happiness in a TextView
.
You can group those views (ImageView, SeekBar, TextView
) into one layout file, then create a new class that extends a layout (e.g. a LinearLayout
or a RelativeLayout
) and write your business logic in it.
Another reason for implementing a custom ViewGroup is if you want to make your custom ViewGroup align its children in a different and unique way. For example, laying out the children in a circle instead of linearly as in the LinearLayout
.
How Android Draws Views
When an Android activity comes up into the foreground, Android asks it for its root view. The root view is the top parent of the layout hierarchy. Android then starts drawing the whole view hierarchy.
Android draws the hierarchy starting from the top parent, then its children, and if one of the children is also a ViewGroup, Android will draw its children before drawing the second child. So it’s a depth-first traversal.
Android draws the children of a ViewGroup
according to the index of the child (its position in the XML file), so the view which you added first will be drawn first.
Android draws the layout hierarchy in three stages:
- Measuring stage: each view must measure itself.
- Layout stage: each ViewGroup finds the right position for its children on the screen by using the child size and also by following the layout rules.
- Drawing stage: after measuring and positioning all of the views, each view happily draws itself. :]