Android Custom Component with Custom Attributes


Advertisements


Following example shows you how to define a simple Android custom component with custom attributes.

Step Description
1 You will use Android studio IDE to create an Android application and name it as DateViewDemo under a package com.example.dateviewdemo as explained in the Hello World Example chapter.
2 Create an XML res/values/attrs.xml file to define new attributes alongwith their data type.
3 Create src/DateView.java file and add the code to define your custom component. It will extend TextView and will have additional functionality to show current date. You will provide attributes parsing logic in of the constructors having AttributeSet as a parameter.
4 Modify res/layout/activity_main.xml file and add the code to create DateView instance along with few default attributes and new attributes.
5 Run the application to launch Android emulator and verify the result of the changes done in the aplication.

Following is the content of the modified main activity file src/com.example.dateviewdemo/MainActivity.java. This file can include each of the fundamental lifecycle methods.

package com.example.dateviewdemo;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the 
      // action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }
}

Following will be the content of res/values/attrs.xml file −

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <declare-styleable name="DateView">
   <attr name="delimiter" format="string"/>
   <attr name="fancyText" format="boolean"/>
   </declare-styleable>
</resources>

Following will be the content of new file src/com.example.dateviewdemo/DateView.java, which will have additional functionality to show current date −

package com.example.dateviewdemo;

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.util.Log;
import android.widget.TextView;

public class DateView extends TextView {
   public String delimiter;
   public boolean fancyText;
   
   public DateView(Context context) {
      super(context);
      setDate();
   }
   
   public DateView(Context context, AttributeSet attrs) {
      super(context, attrs);
      TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DateView );
      final int N = a.getIndexCount();
      for (int i = 0; i < N; ++i) 
      {
         int attr = a.getIndex(i);
         switch (attr)
         {
            case R.styleable.DateView_delimiter:
            delimiter = a.getString(attr);
            setDate();
            break;
            
            case R.styleable.DateView_fancyText:
            fancyText = a.getBoolean(attr, false);
            fancyText();
            break;
         }
      }
      a.recycle();
   }

   public DateView(Context context, AttributeSet attrs, int defStyle) {
      super(context, attrs, defStyle);
      setDate();
   }

   private void setDate() {
      SimpleDateFormat dateFormat = 
      new SimpleDateFormat("yyyy" + delimiter + "MM" + delimiter + "dd");
      String today = dateFormat.format(Calendar.getInstance().getTime());
      setText(today);  // self = DateView = subclass of TextView
   }

   private void fancyText() {
      if( this.fancyText){
         setShadowLayer(9, 1, 1, Color.rgb(44, 44, 40));
      }
   }
}

Following will be the content of res/layout/activity_main.xml file −

<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/com.example.dateviewdemo"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity" >
   
   <com.example.dateviewdemo.DateView
      android:layout_width="match_parent"
      android:layout_height="wrap_content" 
      android:textColor="#fff"
      android:textSize="40sp"
      custom:delimiter="-"
      custom:fancyText="true"
      >
      
</RelativeLayout>

Following will be the content of res/values/strings.xml to define two new constants −

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">DateViewDemo</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
</resources>

Following is the default content of AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.guidemo"
   android:versionCode="1"
   android:versionName="1.0" >
   
   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="22" />
      
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.guidemo.MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      
      </activity>
      
   </application>
</manifest>

Let's try to run your DateViewDemo application. I assume you had created your AVD while doing environment setup. To run the app from Android Studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −

Android Custom Component using Custom Attributes

android_custom_components.htm
Advertisements