Android Custom Components

0
274

Custom components can easily be defined as the implementation of your required components along with the built-in components. This can be achieved by extending the subclass along with your own defined class.

Also Read: Android UI Control

We all know that Android offers a vast range of built-in widgets. From Gallery to RadioButton, from CheckBox to TextView, from EditText to AutoCompleteTextView, and the list goes on and on. These widgets can be used directly in your Android application during the application development phase. But there are times when you want to expand the functionality of your application. The dissatisfaction from the existing functionality of the broad range of available widgets results in the creation of new components which are customized by the developer.

If you want to use an already existing widget or layout with a slight modification then you do it by creating a subclass of the widget. After which, you just need to override its methods. This override of methods will provide you an authorized control over the components of the application.

The below-provided flowchart will help you to understand the creation of custom Views. You can easily include these custom Views in your application by following a few of the simple steps as shown in the figure.

Follow the given step-to-step guide for the creation of a simple custom component.

Step 1: For the creation of this Android application, we will be using Android Studio IDE. Click on the option of New File from the toolbar. Save this application as myapplication. Keep this file under com.example.w3school.myapplication package. This process has already been explained in the Hello World Example chapter.

Step 2: Create an XML file under the name attrs.xml. Store this file in the path res/values/. In this XML file, you will be defining all the required new attributes with their associated data types.

<?xml version=”1.0″ encoding=”utf-8″?>
<resources>
   <declare-styleable name=”TimeView”>
      <declare-styleable name=”TimeView”>
         <attr name=”title” format=”string” />
         <attr name=”setColor” format=”boolean”/>
      </declare-styleable>
   </declare-styleable>
</resources>

Step 3: Create a new Java file and name it as timeview.java. This file will carry the definition for your compound view.

package com.example.w3school.myapplication;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.widget.TextView;

public class TimeView extends TextView
{
   private String titleText;
   private boolean color;

   public TimeView(Context context)
  {
      super(context);
      setTimeView();
   }

   public TimeView(Context context, AttributeSet attrs)
  {
      super(context, attrs);
      // retrieved values correspond to the positions of the attributes
         TypedArray typedArray = context.obtainStyledAttributes(attrs,
            R.styleable.TimeView);
      int count = typedArray.getIndexCount();
      Try
      {         
         for (int i = 0; i < count; ++i)
        {
            int attr = typedArray.getIndex(i);

            // the attr is directly linked to the title attribute
            if(attr == R.styleable.TimeView_title)
            {
               // setting up of text from the layout
               titleText = typedArray.getString(attr);
               setTimeView();
            }
           else if(attr == R.styleable.TimeView_setColor)
           {
               // set the color of the attr “setColor”
               color = typedArray.getBoolean(attr, false);
               decorateText();
            }
         }
      }

      // the recycle() will be executed obligatorily
      finally
      {
         // for reuse
         typedArray.recycle();
      }
   }

   public TimeView(Context context, AttributeSet attrs, int defStyle)
  {
      super(context, attrs, defStyle);
      setTimeView();
   }

   private void setTimeView()
   {
      // has the format hour.minuits am/pm
      SimpleDateFormat dateFormat = new SimpleDateFormat(“hh.mm aa”);
      String time = dateFormat.format(Calendar.getInstance().getTime());
      if(this.titleText != null )
      setText(this.titleText+” “+time);
      else
         setText(time);
   }

   private void decorateText()
  {
      // this works when setColor attribute is true in the XML layout
      if(this.color == true)
      {
         // set the characteristics and the color of the shadow
         setShadowLayer(4, 2, 2, Color.rgb(250, 00, 250));
         setBackgroundColor(Color.CYAN);
      }

      else
      {
         setBackgroundColor(Color.RED);
      }
   }
}

Step 4: After this, you are required to make a few changes in the main activity java file. The changes have to be done so as to define your custom component. You can locate this file here: src/mainactivity.java.

package com.example.w3school.myapplication;
import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity
{
   @Override
   protected void onCreate(Bundle savedInstanceState)
  {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      TextView simpleText = (TextView) findViewById(R.id.simple);
      simpleText.setText(“That is a simple TextView”);
   }
}

Step 5: Now, for the creation of Colour compound view, you need to include the following code in the res/layout/activity_main.xml file. Here, a few of the new attributes will be added along with the already defined default attributes.

<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
   xmlns:tools=”http://schemas.android.com/tools”
   xmlns:custom=”http://schemas.android.com/apk/res-auto”
   android:layout_width=”match_parent”
   android:layout_height=”match_parent”
   tools:context=”.MainActivity” >

   <com.example.w3school.myapplication.TimeView
      android:id=”@+id/timeView”
      android:layout_width=”match_parent”
      android:layout_height=”wrap_content”
      android:textColor=”#fff”
      android:textSize=”40sp”
      custom:title=”my time view”
      custom:setColor=”true” />

   <TextView
      android:layout_width=”match_parent”
      android:layout_height=”wrap_content”
      android:id=”@+id/simple”
      android:layout_below=”@id/timeView”
      android:layout_marginTop=”10dp” />
</RelativeLayout>

Step 6: Finally, run the Android application which will launch the Emulator and all the changes will be verified here. The final output will look appear as the following screenshot.