Android Custom Components Using Layout File

Advertisements


Following example shows you how to define a simple Android custom component and then how to instantiate it inside activity code without using layout file.

StepDescription
1You will use Eclipse 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.
2Create 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.
3Modify res/layout/activity_main.xml file and add the code to create DateView instance along with few default attributes.
4Run the application to launch Android emulator and verify the result of the changes done in the aplication.

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

public class DateView extends TextView {
   public DateView(Context context) {
      super(context);
      setDate();
   }

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

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

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

}

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/layout/activity_main.xml file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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"
     android:background="#000"
     />

</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="17" />

    <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 Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Eclipse 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 Layout File

Advertisements
Advertisements