ideba avatar

Understand and Implement Custom Views in Android - Part 1

ideba

Published: 18 Mar 2019 › Updated: 18 Mar 2019Understand and Implement Custom Views in Android - Part 1

Understand and Implement Custom Views in Android - Part 1

Repository

https://github.com/enyason/custom_view

What Will I Learn?

  • How custom views works
  • How to extend a built in view

Requirements

  • System Requirements : Java JDK, Android Studio
  • OS Support for Java : Windows, mac OS, Linux
  • Required Knowledge : A fair knowledge of Java ,OOP and Android Studio

Resources for Java and this tutorial

  • Difficulty
    Beginner

Tutorial Duration 20- 25 Minutes

Tutorial Content

This is the first part of this tutorial series. By the end of this part 1, we are going to have understanding of custom views in android and how to implement it.

Android Views

we can categorize android built in views into 3:

  • Simple view
  • Container
  • Compound control

The simple view could be a TextField, a TextView or a Button. it displays one simple piece of information.

textfield.png

colored-button.gif

The container contains other views. Example of the container view includes: Linear Layout, Grid View, Relative Layout etc.

GridView

gridview.png

LinearLayout Vs RelativeLayout

linearlayout vs relative layout.jpeg

The compound control is similar to container in that it has multiple views inside of it. It also has specific views inside. Example is a time picker.

TimePicker

time picker.png

Why Custom Views

Most times we would love to have looks and feels that goes far beyond what the android built in views offers. To achieve this we either extend any of the built in views (e.g textview, framelayout ) or we directly extend the view class if we want to have full control of the custom element. The following are advantages of using custom views

  1. Modularize repeated code: Putting code you often use into a custom component
  2. Access protected methods: Inheriting a view gives you access to overriding methods
  3. Optimize rendering speed: You can reduce the number of views you are drawing on screen and hence optimize rendering speed.
  4. Complete control with the draw, measure and layout

Extending Built in Views

The simplest way to build a custom view is to extend a simple view (Android Built in component). To do this, you pick a view that is close to what you need and extend that so that you can reuse the parent class functionality while only writing codes for the parts you need. With this way, you don't have to handle all the drawing and layout complexity.

Steps to Create a custom view

For this tutorial, we are going to extend the text view component

  1. Choose a parent class view closest to what you need. We will use a Text View

  2. we extend textview then we have 3 constructors, 1 for java, 1 for xml, and the other for xml with style

    public class UtopianTextView extends android.support.v7.widget.AppCompatTextView {
        public UtopianTextView(Context context) {
            super(context);
            init();
        }
    
        public UtopianTextView(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
            init();
    
        }
    
        public UtopianTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            init();
    
        }
    
    • After extending the built in text view, we have 3 constructors. Why is because this we can use this view in 3 ways
      • The first constructor allows you create this view in Java
      • The Second and the third are for using in XML. The difference between these two is that the 3rd constructor also allows you specify a style in XML
      • The init() method defines our extra functionalities and is applied to all constructors. This is to ensure the view works as expected regardless of where it's being called, whether java or xml.
  3. Add extra functionality

    void init() {
    
            setText("UtopianDroid");
            setTextSize(20);
            setTextColor(getResources().getColor(R.color.colorPrimary));
            setCompoundDrawablesWithIntrinsicBounds(null,            getResources().getDrawable(R.drawable.ic_android), null, null);
            setOnClickListener(this);
    
        }
    

    In the init()method, add extra functionalities to our custom textview.

    • We first set the text of our view to UtopianDroid
    • Then give it a size of 20 points and the color to primary
    • We give it a top drawable to display an icon on the top.
    • We finally set an onclick listener for the view. Whenever the view is clicked, it will open up the utopian site
     @Override
        public void onClick(View v) {
          Toast.makeText(getContext(),"Hello Utopian",Toast.LENGTH_SHORT).show();
            Uri webPage = Uri.parse("https://utopian.io");
            Intent intent = new Intent(Intent.ACTION_VIEW, webPage);
    
            if (intent.resolveActivity(getContext().getPackageManager()) != null) {
    
                getContext().startActivity(intent);
            }
        }
    
    • This is our onClick method where we put the logic to navigate the user to the webpage.

    • the intent object is created with the action type and uri as parameters.

    • we then navigate to the web page if there is any supported application for the implicit intent defined

Using the custom view we created above should reproduce what is in the image below

utopian_text_view.png

Summary

To create a custom view

  • we extend textview then we have 3 constructors, 1 for java, 1 for xml, and the other for xml with style

  • Choose a parent class view closest to what you need

  • Add extra functionality

Demo video of the app:

Proof of Work The complete source code can be found on gitHub https://github.com/enyason/custom_view

Leave Understand and Implement Custom Views in Android - Part 1 to:

Written by

Android Developer | Java

Read more #utopian-io posts


Best Posts From ideba

We have not curated any of ideba's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From ideba