Showing posts with label Android User Interface. Show all posts
Showing posts with label Android User Interface. Show all posts

Sunday, 18 May 2014

Android Custom Components

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

Android Custom Components
Android offers a great list of pre-built widgets like Button, TextView, EditText, ListView, CheckBox, RadioButton, Gallery, Spinner, AutoCompleteTextView etc. which you can use directly in your Android application development, but there may be a situation when you are not satisfied with existing functionality of any of the available widgets. Android provides you with means of creating your own custom components which you can customized to suit your needs.
If you only need to make small adjustments to an existing widget or layout, you can simply subclass the widget or layout and override its methods which will give you precise control over the appearance and function of a screen element.
This tutorial explains you how to create custom Views and use them in your application using simple and easy steps.

Creating a Simple Custom Component

The simplest way to create your custom component is to extend an existing widget class or subclass with your own class if you want to extend the functionality of existing widget like Button, TextView, EditText, ListView, CheckBox etc. otherwise you can do everything yourself by starting with theandroid.view.View class.
At its simplest form you will have to write your constructors corresponding to all the constructors of the base class. For example if you are going to extend TextView to create a DateView then following three constructors will be created for DateView class:
public class DateView extends TextView {
   public DateView(Context context) {
      super(context);
      //--- Additional custom code --
   }

   public DateView(Context context, AttributeSet attrs) {
      super(context, attrs);
      //--- Additional custom code --
   }

   public DateView(Context context, AttributeSet attrs, int defStyle) {
      super(context, attrs, defStyle);
      //--- Additional custom code --
   }
}
Because you have created DateView as child of TextView so it will have access on all the attributes, methods and events related to TextView and you will be able to use them without any further implementation. You will implement additional custom functionality inside your own code as explained in the given examples below.
If you have requirement for implementing custom drawing/sizing for your custom widgets then you need to override onMeasure(int widthMeasureSpec, int heightMeasureSpec) and onDraw(Canvas canvas) methods. If you are not going to resize or change the shape of your built-in component then you do not need either of these methods in your custom component.
The onMeasure() method coordinate with the layout manager to report the widget's width and height, and you need to call setMeasuredDimension(int width, int height) from inside this method to report the dimensions.
You can then execute your custom drawing inside the onDraw(Canvas canvas) method, where android.graphis.Canvas is pretty similar to its counterpart in Swing, and has methods such as drawRect(), drawLine(), drawString(), drawBitmap() etc. which you can use to draw your component.
Once you are done with the implementation of a custom component by extending existing widget, you will be able to instantiate these custom components in two ways in your application development:

INSTANTIATE USING CODE INSIDE ACTIVITY CLASS

It is very similar way of instantiating custom component the way you instantiate built-in widget in your activity class. For example you can use following code to instantiate above defined custom component:
@Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     
     DateView dateView = new DateView(this);
     setContentView(dateView);
 }
Check this example to understand how to Instantiate a Basic Android Custom Component using code inside an activity.

INSTANTIATE USING LAYOUT XML FILE

Traditionally you use Layout XML file to instantiate your built-in widgets, same concept will apply on your custom widgets as well so you will be able to instantiate your custom component using Layout XML file as explained below. Here com.example.dateviewdemo is the package where you have put all the code related to DateView class and DateView is Java class name where you have put complete logic of your custom component.
<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>
It is important to note here that we are using all TextView attributes along with custom component without any change. Similar way you will be able to use all the events, and methods along with DateView component.
Check this example to understand how to Instantiate a Basic Android Custom Component using Layout XML file.

Custom Component with Custom Attributes

We have seen how we can extend functionality of built-in widgets but in both the examples given above we saw that extended component can make use of all the default attributes of its parent class. But consider a situation when you want to create your own attribute from scratch. Below is a simple procedure to create and use new attributes for Android Custom components. Consider we want to introduce three attributes and will use them as shown below:
<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"
/>

STEP 1

The first step to enable us to use our custom attributes is to define them in a new xml file underres/values/ and call it attrs.xml. Let's have a look on an example 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>
Here the name=value is what we want to use in our Layout XML file as attribute, and the format=type is the type of attribute.

STEP 2

Your second step will be to read these attributes from Layout XML file and set them for the component. This logic will go in the constructors that get passed an AttributeSet, since that is what contains the XML attributes. To read the values in the XML, you need to first create a TypedArray from theAttributeSet, then use that to read and set the values as shown in the below example code:
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:
         String delimiter = a.getString(attr);
         //...do something with delimiter...
         break;
      case R.styleable.DateView_fancyText:
         boolean fancyText = a.getBoolean(attr, false);
         //...do something with fancyText...
         break;
   }
}
a.recycle();

STEP 3

Finally you can use your defined attributes in your Layout XML file as follows:
<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>
The important part isxmlns:custom="http://schemas.android.com/apk/res/com.example.dateviewdemo". Note thathttp://schemas.android.com/apk/res/ will remain as is, but last part will be set to your package name and also that you can use anything after xmlns:, in this example I used custom, but you could use any name you like.
Check this example to understand how to Create Custom Attributes for Android Custom Componentwith simple steps.

Posted By MIrza Abdul Hannan11:35:00 am

Android Styles and Themes

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

Android Styles and Themes
If you already know about Cascading Style Sheet (CSS) in web design then to understand Android Style also works very similar way. There are number of attributes associated with each Android widget which you can set to change your application look and feel. A style can specify properties such as height, padding, font color, font size, background color, and much more.
You can specify these attributes in Layout file as follows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >

   <TextView
   android:id="@+id/text_id"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:capitalize="characters"
   android:textColor="#00FF00"
   android:typeface="monospace"
   android:text="@string/hello_world" />

</LinearLayout>
But this way we need to define style attributes for every attribute separately which is not good for source code maintenance point of view. So we work with styles by defining them in separate file as explained below.

Defining Styles

A style is defined in an XML resource that is separate from the XML that specifies the layout. This XML file resides under res/values/ directory of your project and will have <resources> as the root node which is mandatory for the style file. The name of the XML file is arbitrary, but it must use the .xml extension.
You can define multiple styles per file using <style> tag but each style will have its name that uniquely identifies the style. Android style attributes are set using <item> tag as shown below:
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <style name="CustomFontStyle">
      <item name="android:layout_width">fill_parent</item>
      <item name="android:layout_height">wrap_content</item>
      <item name="android:capitalize">characters</item>
      <item name="android:typeface">monospace</item>
      <item name="android:textSize">12pt</item>
      <item name="android:textColor">#00FF00</item>/> 
   </style>
</resources>
The value for the <item> can be a keyword string, a hex color, a reference to another resource type, or other value depending on the style property.

Using Styles

Once your style is defined, you can use it in your XML Layout file using style attribute as follows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >

   <TextView
   android:id="@+id/text_id"
   style="@style/CustomFontStyle"
   android:text="@string/hello_world" />

</LinearLayout>
To understand the concept related to Android Style, you can check Style Demo Example.

Style Inheritance

Android supports style Inheritance in very much similar way as cascading style sheet in web design. You can use this to inherit properties from an existing style and then define only the properties that you want to change or add.
Its simple, to create a new style LargeFont that inherits the CustomFontStyle style defined above, but make the font size big, you can author the new style like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <style name="CustomFontStyle.LargeFont">
      <item name="android:textSize">20ps</item>
   </style>
</resources>
You can reference this new style as @style/CustomFontStyle.LargeFont in your XML Layout file. You can continue inheriting like this as many times as you'd like, by chaining names with periods. For example, you can extend FontStyle.LargeFont to be Red, with:
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <style name="CustomFontStyle.LargeFont.Red">
      <item name="android:textColor">#FF0000</item>/> 
   </style>
</resources>
This technique for inheritance by chaining together names only works for styles defined by your own resources. You can't inherit Android built-in styles this way. To reference an Android built-in style, such as TextAppearance, you must use the parent attribute as shown below:
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <style name="CustomFontStyle" parent="@android:style/TextAppearance">
      <item name="android:layout_width">fill_parent</item>
      <item name="android:layout_height">wrap_content</item>
      <item name="android:capitalize">characters</item>
      <item name="android:typeface">monospace</item>
      <item name="android:textSize">12pt</item>
      <item name="android:textColor">#00FF00</item>/> 
   </style>
</resources>

Android Themes

Hope you understood the concept of Style, so now let's try to understand what is a Theme. A theme is nothing but an Android style applied to an entire Activity or application, rather than an individual View.
Thus, when a style is applied as a theme, every View in the Activity or application will apply each style property that it supports. For example, you can apply the same CustomFontStyle style as a theme for an Activity and then all text inside that Activity will have green monospace font.
To set a theme for all the activities of your application, open the AndroidManifest.xml file and edit the<application> tag to include the android:theme attribute with the style name. For example:
<application android:theme="@style/CustomFontStyle">
But if you want a theme applied to just one Activity in your application, then add the android:theme attribute to the <activity> tag only. For example:
<activity android:theme="@style/CustomFontStyle">
There are number of default themes defined by Android which you can use directly or inherit them using parent attribute as follows:
<style name="CustomTheme" parent="android:Theme.Light">
    ...
</style>
To understand the concept related to Android Theme, you can check Theme Demo Example.

Default Styles & Themes

The Android platform provides a large collection of styles and themes that you can use in your applications. You can find a reference of all available styles in the R.style class. To use the styles listed here, replace all underscores in the style name with a period. For example, you can apply the Theme_NoTitleBar theme with "@android:style/Theme.NoTitleBar". You can see the following source code for Android styles and themes:

Posted By MIrza Abdul Hannan11:33:00 am

Android Event Handling

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

Android Event Handling
Events are a useful way to collect data about a user's interaction with interactive components of your app, like button presses or screen touch etc. The Android framework maintains an event queue into which events are placed as they occur and then each event is removed from the queue on a first-in, first-out (FIFO) basis. You can capture these events in your program and take appropriate action as per requirements.
There are following three concepts related to Android Event Management:
  • Event Listeners: The View class is mainly involved in building up a Android GUI, same View class provides a number of Event Listeners. The Event Listener is the object that receives notification when an event happes.
  • Event Listeners Registration: Event Registration is the process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event.
  • Event Handlers: When an event happens and we have registered and event listener fo the event, the event listener calls the Event Handlers, which is the method that actually handles the event.

Event Listeners & Event Handlers

Event HandlerEvent Listener & Description
onClick()OnClickListener()
This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc. You will use onClick() event handler to handle such event.
onLongClick()OnLongClickListener()
This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc. for one or more seconds. You will use onLongClick() event handler to handle such event.
onFocusChange()OnFocusChangeListener()
This is called when the widget looses its focus ie. user goes away from the view item. You will use onFocusChange() event handler to handle such event.
onKey()OnFocusChangeListener()
This is called when the user is focused on the item and presses or releases a hardware key on the device. You will use onKey() event handler to handle such event.
onTouch()OnTouchListener()
This is called when the user presses the key, releases the key, or any movement gesture on the screen. You will use onTouch() event handler to handle such event.
onMenuItemClick()OnMenuItemClickListener()
This is called when the user selects a menu item. You will use onMenuItemClick() event handler to handle such event.
There are many more event listeners available as a part of View class like OnHoverListener, OnDragListener etc which may be needed for your application. So I recommend to refer official documentation for Android application development in case you are going to develop a sophisticated apps.

Event Listeners Registration:

Event Registration is the process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event. Though there are several tricky ways to register your event listener for any event, but I'm going to list down only top 3 ways, out of which you can use any of them based on the situation.
  • Using an Anonymous Inner Class
  • Activity class implements the Listener interface.
  • Using Layout file activity_main.xml to specify event handler directly.
Below section will provide you detailed examples on all the three scenarios:

Event Handling Examples

EVENT LISTENERS REGISTRATION USING AN ANONYMOUS INNER CLASS

Here you will create an anonymous implementation of the listener and will be useful if each class is applied to a single control only and you have advantage to pass arguments to event handler. In this approach event handler methods can access private data of Activity. No reference is needed to call to Activity.
But if you applied the handler to more than one control, you would have to cut and paste the code for the handler and if the code for the handler is long, it makes the code harder to maintain.
Following are the simple steps to show how we will make use of separate Listener class to register and capture click event. Similar way you can implement your listener for any other required event type.
StepDescription
1You will use Eclipse IDE to create an Android application and name it as EventDemo under a package com.example.eventdemo as explained in the Hello World Example chapter.
2Modify src/MainActivity.java file to add click event listeners and handlers for the two buttons defined.
3Modify the detault content of res/layout/activity_main.xml file to include Android UI controls.
4Define required constants in res/values/strings.xml file
5Run 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 filesrc/com.example.eventdemo/MainActivity.java. This file can include each of the fundamental lifecycle methods.
package com.example.eventdemo;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //--- find both the buttons---
        Button sButton = (Button) findViewById(R.id.button_s);
        Button lButton = (Button) findViewById(R.id.button_l);
        
        // -- register click event with first button ---
        sButton.setOnClickListener(new View.OnClickListener() {
           public void onClick(View v) {
               // --- find the text view --
               TextView txtView = (TextView) findViewById(R.id.text_id);
               // -- change text size --
               txtView.setTextSize(14);
           }
        });
        
        // -- register click event with second button ---
        lButton.setOnClickListener(new View.OnClickListener() {
           public void onClick(View v) {
               // --- find the text view --
               TextView txtView = (TextView) findViewById(R.id.text_id);
               // -- change text size --
               txtView.setTextSize(24);
           }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}
Following will be the content of res/layout/activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >


    <Button 
    android:id="@+id/button_s"
    android:layout_height="wrap_content" 
    android:layout_width="match_parent" 
    android:text="@string/button_small"/>
    
    <Button 
    android:id="@+id/button_l"
    android:layout_height="wrap_content" 
    android:layout_width="match_parent" 
    android:text="@string/button_large"/>

    <TextView
    android:id="@+id/text_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:capitalize="characters"
    android:text="@string/hello_world" />

</LinearLayout>
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">EventDemo</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
   <string name="button_small">Small Font</string>
   <string name="button_large">Large Font</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 EventDemo 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 Event Handling
Now you try to click on two buttons one by one and you will see that font of the Hello World text will change, which happens because registered click event handler method is being called against each click event.

REGISTRATION USING THE ACTIVITY IMPLEMENTS LISTENER INTERFACE

Here your Activity class implements the Listener interface and you put the handler method in the main Activity and then you call setOnClickListener(this).
This approach is fine if your application has only a single control of that Listener type otherwise you will have to do further programming to check which control has generated event. Second you cannot pass arguments to the Listener so, again, works poorly for multiple controls.
Following are the simple steps to show how we will implement Listener class to register and capture click event. Similar way you can implement your listener for any other required event type.
StepDescription
1We do not need to create this application from scratch, so let's make use of above created Android application EventDemo.
2Modify src/MainActivity.java file to add click event listeners and handlers for the two buttons defined.
3We are not making any change in res/layout/activity_main.xml, it will remain as shown above.
4We are also not making any change in res/values/strings.xml file, it will also remain as shown above.
5Run 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 filesrc/com.example.eventdemo/MainActivity.java. This file can include each of the fundamental lifecycle methods.
package com.example.eventdemo;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //--- find both the buttons---
        Button sButton = (Button) findViewById(R.id.button_s);
        Button lButton = (Button) findViewById(R.id.button_l);
        
        
        // -- register click event with first button ---
        sButton.setOnClickListener(this);
        // -- register click event with second button ---
        lButton.setOnClickListener(this);
    }
        
    //--- Implement the OnClickListener callback
    public void onClick(View v) {
       if(v.getId() == R.id.button_s)
       { 
            // --- find the text view --
            TextView txtView = (TextView) findViewById(R.id.text_id);
            // -- change text size --
            txtView.setTextSize(14);
            return;
       }
       if(v.getId() == R.id.button_l)
       { 
            // --- find the text view --
            TextView txtView = (TextView) findViewById(R.id.text_id);
            // -- change text size --
            txtView.setTextSize(24);
            return;
       }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}
Now again let's try to run your EventDemo 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 Event Handling
Now you try to click on two buttons one by one and you will see that font of the Hello World text will change, which happens because registered click event handler method is being called against each click event.

REGISTRATION USING LAYOUT FILE ACTIVITY_MAIN.XML

Here you put your event handlers in Activity class without implementing a Listener interface or call to any listener method. Rather you will use the layout file (activity_main.xml) to specify the handler method via the android:onClick attribute for click event. You can control click events differently for different control by passing different event handler methods.
The event handler method must have a void return type and take a View as an argument. However, the method name is arbitrary, and the main class need not implement any particular interface.
This approach does not allow you to pass arguments to Listener and for the Android developers it will be difficult to know which method is the handler for which control until they look into activity_main.xml file. Second, you can not handle any other event except click event using this approach.
Following are the simple steps to show how we can make use of layout file Main.xml to register and capture click event.
StepDescription
1We do not need to create this application from scratch, so let's make use of above created Android application EventDemo.
2Modify src/MainActivity.java file to add click event listeners and handlers for the two buttons defined.
3Modify layout file res/layout/activity_main.xml, to specify event handlers for the two buttons.
4We are also not making any change in res/values/strings.xml file, it will also remain as shown above.
5Run 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 filesrc/com.example.eventdemo/MainActivity.java. This file can include each of the fundamental lifecycle methods.
package com.example.eventdemo;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
        
    //--- Implement the event handler for the first button.
    public void doSmall(View v)  {
       // --- find the text view --
       TextView txtView = (TextView) findViewById(R.id.text_id);
       // -- change text size --
       txtView.setTextSize(14);
       return;
   }
   //--- Implement the event handler for the second button.
   public void doLarge(View v)  {
       // --- find the text view --
       TextView txtView = (TextView) findViewById(R.id.text_id);
       // -- change text size --
       txtView.setTextSize(24);
       return;
   }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}
Following will be the content of res/layout/activity_main.xml file. Here we have to addandroid:onClick="methodName" for both the buttons, which will register given method names as click event handlers.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >


    <Button 
    android:id="@+id/button_s"
    android:layout_height="wrap_content" 
    android:layout_width="match_parent" 
    android:text="@string/button_small"
    android:onClick="doSmall"/>
    
    <Button 
    android:id="@+id/button_l"
    android:layout_height="wrap_content" 
    android:layout_width="match_parent" 
    android:text="@string/button_large"
    android:onClick="doLarge"/>

    <TextView
    android:id="@+id/text_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:capitalize="characters"
    android:text="@string/hello_world" />

</LinearLayout>
Again let's try to run your EventDemo 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 Event Handling
Now you try to click on two buttons one by one and you will see that font of the Hello World text will change, which happens because registered click event handler method is being called against each click event.

Exercise:

I will recommend to try writing different event handlers for different event types and understand exact difference in different event types and their handling. Events related to menu, spinner, pickers widgets are little different but they are also based on the same concepts as explained above.

Posted By MIrza Abdul Hannan11:32:00 am