Tuesday, January 27, 2009

Code: Add a custom menu item to an existing BlackBerry application


Procedure

The ApplicationMenuItem class will allow the addition of a custom menu item to various screens within BlackBerry specific applications, or as a system-wide setting. The following example illustrates how to add a menu item to the email view screen.

Obtain an instance of the MenuItemRepository to add the menu item.
Code:
myMenuItem myMenuitem = new MyMenuItem(0);

ApplicationMenuItemRepository
.getInstance().addMenuItem
(ApplicationMenuItemRepository
.MENUITEM_EMAIL_VIEW,myMenuitem);

Create a class so that certain methods within the ApplicationMenuItem class can be overridden.

Code

class MyMenuItem extends ApplicationMenuItem{
 
    //using the default constructors here.
    MyMenuItem(int order){
        super(order);
    }
 
    //methods we must implement
    //Run is called when the menuItem is invoked
    public Object run(Object context){
        //context object should be a email message
        if (context instanceof Message){
            Message message = (Message)context;
            //this is where we would work the message
          //do something here
        }
        return context;
    }
 
    //toString should return the string we want to
    //use as the lable of the menuItem
    public String toString(){
        return "MyMenu Name";
    }
}

It should be noted that Object context that is passed into the run method will depend on the screen to which the menu item has been added. In this example, the context is an email message because the menu item has been added to the email view screen. If the item was added to the address book, it would return a personal information management (PIM) item.

No comments:

Post a Comment

Place your comments here...