Android Custom Views (Components) with Examples

  Total Views : 42
  Comments : 0
  Keywords : Android custom components to build our own custom view components, Android custom components to extend the functionality of default views

Here we will learn custom views or components in android with examples, creare custom view components in android, define custom attributes in android, apply custom attributes in android  and how to create our own custom view components by extending the functionality of default views in android with examples.

Android Custom View Components

Android provides a powerful built-in View components such as Button, TextView, EditText, ListView, Gridview, Spinner, etc. and layouts like LinearLayout, RelativeLayout, FrameLayout, etc. to build our application UI based on our requirements.

 

In android, we can create our own custom components in case, if we are not satisfied with the built-in widgets or layouts functionality.

 

In case, if we want to extend the functionality of an existing built-in widget or layout, we can do it by overriding the methods of widget or layout based on our requirements.

 

If we create our own custom components, we will have a great control over the functionality and appearance of View elements in our application.

 

Now we will learn how to create and use custom Views in our android applications.

Android Create Custom View Components

In android, creating a custom view component is something similar to defining a class in Java. Following is the high level overview of what we need to know to get started in creating our own View components in android applications.

 

  • We need to extend an existing View class or subclass with our own class.
  • Need to override some of the methods from superclass based on our requirements. The superclass methods which we are going to override should start with 'on' like onDraw() or onKeyDown(). This is similar to on... events in Activity or ListActivity that we want to override for lifecycle and other functionality hooks.
  • Once we are done with creation of our new extension class, we need to use it in the place of View.

While creating a custom component, we need to remember that it should provide an easy interface to use it in our applications and allow users to configure custom style attributes from android XML layouts.

 

Following is the example of creating a custom View by extending the default view such as TextView in android application.

 

package com.tutlane.customcomponents;
import android.content.Context;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;

/**
 * Created by tutlane on 02-11-2017.
 */

public class TutlaneView extends AppCompatTextView {
   
public TutlaneView(Context context){
       
super(context);
    }
   
public TutlaneView(Context context, AttributeSet attributeSet){
       
super(context,attributeSet);
    }
   
public TutlaneView(Context context,AttributeSet attributeSet, int defStyle){
       
super(context,attributeSet,defStyle);
    }
}

Android Define Custom Attributes

As we discussed, we need to allow users to configure custom attributes from android XML layouts to control the behaviour and appearance of custom view in our applications.

 

Following is the example of creating an attributes for custom view in android XML layout.

 

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <
declare-styleable name="TutlaneView">
        <
attr name="setColor" format="boolean"/>
        <
attr name="settitle" format="string"/>
     </
declare-styleable>
</
resources>

Once we are done with creation of custom attributes, we can use those attributes in our layout files like as shown below.

 

<com.tutlane.customcomponents.TutlaneView
   
android:layout_width="wrap_content"
   
android:layout_height="wrap_content"
   
app:settitle="Welcome to Tutlane"
   
app:setColor="true" />

If you observe above code snippet, we are accessing custom view with name and using custom attributes properties in XML layout file.

Android Apply Custom Attributes

When a view is created from XML layout, the attributes in XML are read from the resource bundle and passed into the view’s constructor as an AttributeSet. We can read the attributes by calling obtainStyledAttributes() method.

 

Following is the example of reading custom attributes using obtainStyledAttributes() method from XML.

 

TypedArray tarry = context.obtainStyledAttributes(attributeSet,R.styleable.TutlaneView);
   
title = tarry.getString(R.styleable.TutlaneView_settitle);
   
if(title == null)
    setText(
"Custom Message");
   
else
       
setText("Welcome to Tutlane");
   
color = tarry.getBoolean(R.styleable.TutlaneView_setColor, false);
   
if(color == true)
    setTextColor(Color.
MAGENTA);

If you observe above code snippet, we are reading custom attributes from XML and updating those attributes based on our requirements.

Android Custom Views Example

Following is the example of creating a custom view by extending the built-in TextView control in android application.

 

Create a new android application using android studio and give names as CustomComponents. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

 

Now we need to define our custom view for that create a new class file (TutlaneView.java) in \java\com.tutlane.customcomponents folder and write the code like as shown below.

TutlaneView.java

package com.tutlane.customcomponents;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;

/**
 * Created by surdasari on 02-11-2017.
 */

public class TutlaneView extends AppCompatTextView {
   
private String title;
   
private boolean color;
   
public TutlaneView(Context context){
       
super(context);
    }
   
public TutlaneView(Context context, AttributeSet attributeSet){
       
super(context,attributeSet);
        TypedArray tarry = context.obtainStyledAttributes(attributeSet,R.styleable.
TutlaneView);
       
try {
           
title = tarry.getString(R.styleable.TutlaneView_settitle);
           
if(title == null)
            setText(
"Custom Message");
           
else
               
setText("Welcome to Tutlane");
           
color = tarry.getBoolean(R.styleable.TutlaneView_setColor, false);
           
if(color == true)
            setTextColor(Color.
MAGENTA);
        }
       
finally {
            tarry.recycle();
        }
    }
   
public TutlaneView(Context context,AttributeSet attributeSet, int defStyle){
       
super(context,attributeSet,defStyle);
    }
}

If you observe above code, we used custom attributes such as settitle and setColor for our custom view. We need to define our custom attributes for that create a new class file (customattr.xml) in \res\values folder and write the code like as shown below.

customattr.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <
declare-styleable name="TutlaneView">
        <
attr name="setColor" format="boolean"/>
        <
attr name="settitle" format="string"/>
    </
declare-styleable>
</
resources>

To use our custom view component in our application, we need to open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
xmlns:app="http://schemas.android.com/apk/res-auto"
   
android:orientation="vertical">
<
com.tutlane.customcomponents.TutlaneView
   
android:layout_width="wrap_content"
   
android:layout_height="wrap_content"
   
app:settitle="Welcome to Tutlane"
   
app:setColor="true"
   
android:layout_marginTop="200dp"
   
android:layout_marginLeft="120dp"
   
android:textStyle="bold"
   
android:textSize="18dp"/>
</
LinearLayout>

If you observe above code, we used a custom view component by referring with custom view name. Once we are done with adding required custom view components, we need to load the XML layout resource from our activity onCreate() callback method, for that open main activity file MainActivity.java from \java\com.tutlane.customcomponents path and write the code like as shown below.

MainActivity.java

package com.tutlane.customcomponents;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
    }
}

Generally, during the launch of our activity, onCreate() callback method will be called by android framework to get the required layout for an activity.

Output of Android Custom Views Example

When we run above example using android virtual device (AVD) we will get a result like as shown below.

 

Android Custom View Components Example Result

 

If you observe above result, we are able to show our custom view component with custom attributes in our application.

 

This is how we can create custom view components in our application to extend the behaviour of existing built-in views or we can complete new custom views based on our requirements. 

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User