In my previous post, I talked about class Attributes on Activities.
This post is about overriding event methods to influence the behavior of the Activity.

Activity LifeCycle

When a new Activity is created, the template overrides one event method; OnCreate.

[Activity]
public class MyActivity : Activity
{
    protected override void OnCreate(Bundle bundle)
    {
       .....
    }
}

The OnCreate is part of the Activity LifeCycle.
It is important to understand the Activity LifeCycle, it is one of the fundamentals of an android application.
The OnCreate method works like the Page_Load method of a WebForms page.
This is ideal for setting up the Activity.

For instance:

  • loading layout files
  • updating controls
  • binding event handlers

All event methods of the Activity LifeCycle:

  • OnCreate
  • OnStart
  • OnResume
  • OnPause
  • OnStop
  • OnDestroy
  • OnRestart

When an activity changes state, the corresponding event method is called.
All these methods can be overridden and implemented.

The Activity exposes a lot more overridable event methods.
These are methods I use a lot:

Options menu

The following event methods are used for controlling the options menu:

public override bool OnPrepareOptionsMenu(IMenu menu)
{
       // add your options items to the menu here
      return base.OnPrepareOptionsMenu(menu);
}

public override bool OnOptionsItemSelected(IMenuItem item)
{
    // detect selected menu item and handle action
    return base.OnOptionsItemSelected(item);
}

The OnPrepareOptionsMenu is called when the options menu is created. Custom options can be added to the menu argument.
When an option item is clicked, the OnOptionsItemSelected is called with the selected option item as argument. I usually use a switch on item.Id to detect which item is selected.

The back button

The following event method is called when the back button is pressed:

public override void OnBackPressed()
{
    // handle back button
    base.OnBackPressed();
}

the base.OnBackPressed() provides the default back button behavior. Remove this line when you want to disable the default back button behavior, but I do not recommend it. People expect this behavior from the back button.

Creating Dialogs

This following event method is called when ShowDialog() is called in the current Activity.

public override Dialog OnCreateDialog(Bundle savedInstanceState)
{
    // Create and return dialog here.
}

This method is used to create a dialog.

This should help you get on your way with creating your Activities.

The following two tabs change content below.
I'm a software developer from Utrecht. Interested in DDD, continuous delivery, new technologies & frameworks.

Latest posts by Vincent Keizer (see all)