• Save
Black berry java_sdk-development_guide--1239696-0730090812-001-6.0-us
Upcoming SlideShare
Loading in...5
×
 

Black berry java_sdk-development_guide--1239696-0730090812-001-6.0-us

on

  • 352 views

 

Statistics

Views

Total Views
352
Views on SlideShare
352
Embed Views
0

Actions

Likes
0
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Black berry java_sdk-development_guide--1239696-0730090812-001-6.0-us Black berry java_sdk-development_guide--1239696-0730090812-001-6.0-us Document Transcript

  • BlackBerry Java SDKUI and NavigationVersion: 6.0Development Guide
  • Published: 2010-12-8SWD-1239696-1208103942-001
  • Contents1 Creating a UI that is consistent with standard BlackBerry UIs........................................................................................... 62 BlackBerry device user input and navigation.......................................................................................................................... 7Touch screen.................................................................................................................................................................................... 7Trackball or trackpad...................................................................................................................................................................... 9Trackball sensitivity................................................................................................................................................................ 9Trackball movement............................................................................................................................................................... 9Trackwheel....................................................................................................................................................................................... 9Keyboard.......................................................................................................................................................................................... 10Interaction methods on BlackBerry devices................................................................................................................................ 103 Screens.......................................................................................................................................................................................... 11Screen classes................................................................................................................................................................................. 11Manage a drawing area................................................................................................................................................................. 12Creating a screen transition.......................................................................................................................................................... 13Code sample: Creating a screen transition......................................................................................................................... 14Specifying the orientation and direction of the screen.............................................................................................................. 15Retrieve the orientation of the touch screen...................................................................................................................... 17Restrict the touch screen direction...................................................................................................................................... 17Receive notification when the size of the drawable area of the touch screen changes................................................ 174 Accelerometer.............................................................................................................................................................................. 19Types of accelerometer data.......................................................................................................................................................... 19Retrieving accelerometer data...................................................................................................................................................... 19Retrieve accelerometer data at specific intervals....................................................................................................................... 20Query the accelerometer when the application is in the foreground...................................................................................... 21Query the accelerometer when the application is in the background..................................................................................... 21Store accelerometer readings in a buffer..................................................................................................................................... 22Retrieve accelerometer readings from a buffer........................................................................................................................... 23Get the time a reading was taken from the accelerometer....................................................................................................... 235 Events............................................................................................................................................................................................ 24Respond to navigation events....................................................................................................................................................... 24Determine the type of input method............................................................................................................................................ 24Touch screen interaction models.................................................................................................................................................. 25 View slide
  • Responding to touch screen events.............................................................................................................................................. 26Respond to system events while the user touches the screen.......................................................................................... 27Respond to a user sliding a finger up quickly on the screen............................................................................................. 27Respond to a user sliding a finger down quickly on the screen........................................................................................ 28Respond to a user sliding a finger to the left quickly on the screen................................................................................ 29Respond to a user sliding a finger to the right quickly on the screen............................................................................. 29Respond to a user clicking the screen................................................................................................................................. 30Respond to a user touching the screen twice quickly........................................................................................................ 31Respond to a user touching and dragging an item on the screen................................................................................... 31Respond to a user touching the screen lightly................................................................................................................... 32Respond to a scroll action..................................................................................................................................................... 32Respond to a user touching the screen in two locations at the same time..................................................................... 33Pinch gestures................................................................................................................................................................................. 34Enable pinch gestures............................................................................................................................................................ 34Swipe gestures with trackpads...................................................................................................................................................... 35Enable swipe gestures that users make on the trackpad.................................................................................................. 36Event injection................................................................................................................................................................................. 376 Command Framework API.......................................................................................................................................................... 38Use a command with one UI component.................................................................................................................................... 39Use a command in one or more applications.............................................................................................................................. 407 Arranging UI components.......................................................................................................................................................... 43Arrange UI components................................................................................................................................................................. 44Creating a grid layout..................................................................................................................................................................... 44Create a grid layout................................................................................................................................................................ 46Displaying fields on a temporary pair of managers.................................................................................................................... 48Display a ButtonField and a LabelField temporarily on the top and bottom of the screen........................................... 49Displaying a field at an absolute position on a screen............................................................................................................... 51Display a label at an absolute position on the screen....................................................................................................... 51Code sample: Displaying a label at an absolute position on the screen......................................................................... 528 UI components............................................................................................................................................................................. 54Add a UI component to a screen.................................................................................................................................................. 54Aligning a field to a line of text..................................................................................................................................................... 54Buttons............................................................................................................................................................................................. 54 View slide
  • Best practice: Implementing buttons................................................................................................................................... 55Create a button....................................................................................................................................................................... 55Check boxes..................................................................................................................................................................................... 56Best practice: Implementing check boxes........................................................................................................................... 56Create a check box................................................................................................................................................................. 57Create a bitmap............................................................................................................................................................................... 59Create a custom field...................................................................................................................................................................... 59Creating a field to display web content....................................................................................................................................... 62Display HTML content in a browser field............................................................................................................................ 62Display HTML content from a web page in a browser field.............................................................................................. 64Display HTML content from a resource in your application.............................................................................................. 65Configure a browser field...................................................................................................................................................... 67Send form data to a web address in a browser field.......................................................................................................... 69Dialog boxes.................................................................................................................................................................................... 71Best practice: Implementing dialog boxes.......................................................................................................................... 72Create a dialog box................................................................................................................................................................ 74Drop-down lists............................................................................................................................................................................... 74Best practice: Implementing drop-down lists..................................................................................................................... 75Create a drop-down list......................................................................................................................................................... 75Labels................................................................................................................................................................................................ 77Best practice: Implementing labels...................................................................................................................................... 78Create a text label.................................................................................................................................................................. 78Lists and tables................................................................................................................................................................................ 78Best practice: Implementing lists and tables...................................................................................................................... 81Create a list box...................................................................................................................................................................... 81Radio buttons.................................................................................................................................................................................. 83Best practice: Implementing radio buttons......................................................................................................................... 84Create a radio button............................................................................................................................................................. 84Activity indicators and progress indicators.................................................................................................................................. 86Best practice: Implementing activity indicators and progress indicators....................................................................... 87Indicating activity or task progress...................................................................................................................................... 88Pickers.............................................................................................................................................................................................. 96Best practice: Implementing pickers.................................................................................................................................... 98Create a date picker............................................................................................................................................................... 99Create a file picker................................................................................................................................................................. 101
  • Search............................................................................................................................................................................................... 104Best practice: Implementing search.................................................................................................................................... 105Create a search field.............................................................................................................................................................. 106Autocomplete text field......................................................................................................................................................... 108Spin boxes........................................................................................................................................................................................ 114Create a spin box.................................................................................................................................................................... 115Best practice: Implementing spin boxes.............................................................................................................................. 118Text fields......................................................................................................................................................................................... 118Best practice: Implementing text fields............................................................................................................................... 119Creating a text field................................................................................................................................................................ 120Create a date field.................................................................................................................................................................. 121Create a password field......................................................................................................................................................... 122Tree views......................................................................................................................................................................................... 122Best practice: Implementing tree views.............................................................................................................................. 123Create a field to display a tree view..................................................................................................................................... 1239 Images........................................................................................................................................................................................... 125Using encoded images................................................................................................................................................................... 125Access an encoded image through an input stream.......................................................................................................... 125Encode an image.................................................................................................................................................................... 125Display an encoded image.................................................................................................................................................... 126Specify the display size of an encoded image.................................................................................................................... 126Specify the decoding mode for an image............................................................................................................................ 126Displaying an image for zooming and panning.......................................................................................................................... 126Code sample: Displaying an image for zooming and panning......................................................................................... 127Display an image for zooming and panning....................................................................................................................... 127Displaying a row of images for scrolling...................................................................................................................................... 128Code sample: Displaying a row of images for scrolling..................................................................................................... 128Display a row of images for scrolling................................................................................................................................... 12910 Menu items................................................................................................................................................................................... 132Create a menu................................................................................................................................................................................. 132Code sample: Creating a menu............................................................................................................................................ 133Best practice: Implementing menus............................................................................................................................................. 134Submenus........................................................................................................................................................................................ 134Best practice: Implementing submenus.............................................................................................................................. 136
  • Create a submenu.................................................................................................................................................................. 137Code sample: Creating a submenu...................................................................................................................................... 138Pop-up menus................................................................................................................................................................................. 139Best practice: Implementing pop-up menus....................................................................................................................... 140About placing items in the pop-up menus.......................................................................................................................... 141Support for legacy context menus........................................................................................................................................ 141Creating a pop-up menu....................................................................................................................................................... 142Adding a menu item to a BlackBerry Device Software application.......................................................................................... 147Add a menu item to a BlackBerry Device Software application....................................................................................... 147Changing the appearance of a menu........................................................................................................................................... 149Change the appearance of a menu...................................................................................................................................... 149Code sample: Changing the appearance of a menu.......................................................................................................... 15011 Custom fonts................................................................................................................................................................................ 153Install and use a custom font in a BlackBerry Java application................................................................................................ 153Code sample: Installing and using a custom font in a BlackBerry Java application............................................................... 15412 Spelling checker.......................................................................................................................................................................... 156Add spell check functionality......................................................................................................................................................... 156Listen for a spell check event........................................................................................................................................................ 15713 Related resources........................................................................................................................................................................ 15814 Glossary......................................................................................................................................................................................... 15915 Provide feedback......................................................................................................................................................................... 16016 Document revision history......................................................................................................................................................... 16117 Legal notice.................................................................................................................................................................................. 164
  • Creating a UI that is consistent with standard BlackBerryUIs1You can use the standard MIDP APIs and the BlackBerry® UI APIs to create a BlackBerry® Java® Application UI.The UI components in the BlackBerry UI APIs are designed to provide layouts and behaviors that are consistent with BlackBerry®Device Software applications. Using these APIs not only allows you to use components that BlackBerry users are familiar with,but it also saves you time since you dont have to create those components yourself.• Screen components can provide a standard screen layout, a default menu, and standard behavior when a BlackBerry deviceuser presses the Escape key, clicks the trackpad, or touches the touch screen.• Field components can provide the standard UI elements for date selection, option button, check box, list, text field, label,and progress bar controls.• Layout managers can provide an application with the ability to arrange the components on a BlackBerry device screen instandard ways, such as horizontally, vertically, or in a left-to-right flow.You can use the BlackBerry UI APIs to create a UI that includes tables, grids, and other specialized features. You can use astandard Java event model to receive and respond to specific types of events. A BlackBerry device application can receive andrespond to user events, such as when the user clicks the trackpad or types on the keyboard, and to system events, such as globalalerts, clock changes, and USB port connections.Development Guide Creating a UI that is consistent with standard BlackBerry UIs6
  • BlackBerry device user input and navigation 2BlackBerry® devices include a keyboard, a trackwheel, trackball, or trackpad, and an Escape key, for input and navigation. OnBlackBerry devices with a SurePress™ touch screen, clicking the screen is equivalent to clicking the trackball or trackwheel.A BlackBerry® Java® Application should use the following input and navigation model as closely as possible.• Clicking the trackwheel, trackball, trackpad, or touch screen typically invokes a menu.• Pressing the Escape key cancels actions or returns to the previous screen. Pressing the Escape key repeatedly returns usersto the Home screen. Holding the Escape key closes the browser or media application.By default, the BlackBerry screen objects provide this functionality without customization; however, you must add menu itemsand additional UI and navigation logic.Touch screenOn BlackBerry® devices with a SurePress™ touch screen, users use a finger to interact with the applications on the device. Userstype text and navigate screens by performing various actions on the touch screen.Users can also perform actions by clicking icons on the shortcut bar or by pressing the Menu key.On BlackBerry devices with a touch screen, users can perform the following actions:Action Resulttouch the screen lightly This action highlights an item.In a text field, if users touch the screen near the cursor, an outlined box displaysaround the cursor. This box helps users reposition the cursor more easily.tap the screen In applications that support a full-screen view, such as BlackBerry® Maps and theBlackBerry® Browser, this action hides and shows the shortcut bar.tap the screen twice On a web page, map, picture, or presentation attachment, this action zooms in tothe web page, map, picture, or presentation attachment.hold a finger on an item On the shortcut bar, this action displays a tooltip that describes the action that theicon represents.In a message list, if users hold a finger on the sender or subject of a message, theBlackBerry device searches for the sender or subject.Development Guide BlackBerry device user input and navigation7
  • Action Resulttouch and drag an item on the screen This action moves the content on the screen in the corresponding direction. Forexample, when users touch and drag a menu item, the list of menu items moves inthe same direction.Inatextfield,thisactionmovestheoutlinedboxandthecursorinthesamedirection.touch the screen in two locations at thesame timeThis action highlights the text or the list of items, such as messages, between thetwolocations.Toaddorremovehighlightedtextoritems,userscantouchthescreenat another location.click (press) the screen This action initiates an action. For example, when users click an item in a list, thescreen that is associated with the item appears. This action is equivalent to clickingthe trackwheel, trackball or trackpad.On a map, picture, or presentation attachment, this action zooms in to the map,picture, or presentation attachment. On a web page, this action zooms in to theweb page or follows a link.In a text field, this action positions the cursor. If the field contains text, an outlinedbox appears around the cursor.slide a finger up or down quickly on thescreenQuickly sliding a finger up displays the next screen. Quickly sliding a finger downdisplays the previous screen.When the keyboard appears, quickly sliding a finger down hides the keyboard anddisplays the shortcut bar.slide a finger to the left or right quicklyon the screenThis action displays the next or previous picture or message, or the next or previousday, week, or month in a calendar.slide a finger up or down on the screen In the camera, sliding a finger up zooms in to a subject. Sliding a finger down zoomsout from a subject.slide a finger in any direction This action pans a map or web page. If users zoom in to a picture, this action alsopans a picture.press the Escape key This action removes the highlight from text or a list of items.On a web page, map, or picture, this action zooms out one level. Users can pressthe Escape key twice to zoom back to the original view.Development Guide Touch screen8
  • Trackball or trackpadOn BlackBerry® devices with a trackball or trackpad, the trackball or trackpad is the primary control for user navigation. Userscan perform the following actions:• Roll the trackball or slide a finger on the trackpad to move the cursor.• Click the trackball or trackpad to perform default actions or open a context menu.• Click the trackball or trackpad while pressing the Shift key to highlight text or highlight messages in a message list.BlackBerry devices with a trackball or trackpad also include a Menu key that is located to the left of the trackball or trackpad.Users can press the Menu key to open a full menu of available actions.Trackball sensitivityTrackballsensitivityreferstotheamountoftrackballmovementthatthesystemrequirestoidentifythemovementasanavigationevent, and to send a navigation event to the software layer. The BlackBerry® device hardware measures physical trackballmovementbyusingunitscalledticks.WhenthenumberofticksalonganaxissurpassesthethresholdofthesystemoraBlackBerrydevice application, a navigation event is sent to the software layer, and the system resets the tick count to zero. Tick counts arealso reset to zero after a certain amount of idle time passes.You can use the Trackball API to set the trackball sensitivity. High trackball sensitivity equates to a smaller tick threshold (a smallamount of trackball movement generates a navigation event). Low trackball sensitivity equates to a larger tick threshold (a largeramount of trackball movement is required to generate a navigation event).Trackball movementYou can use the Trackball API to filter the trackball movement data that the BlackBerry® device hardware sends to the softwarelayer. The Trackball API can filter out movement "noise" or unwanted movements.YoucanalsousetheTrackballAPItochangesettingssuchastrackballmovementacceleration.Increasingthetrackballmovementacceleration setting can result in the software layer identifying trackball movements as moving at a faster rate than the ratedetectedbytheBlackBerrydevicehardware,aslongastheusercontinuallyrollsthetrackball.Thetrackballsensitivitytemporarilyincreases as the user rolls the trackball without pausing.TrackwheelBlackBerry®devicesthatprecedetheBlackBerry®Pearl™8100Seriesuseatrackwheelastheprimarycontrolforusernavigation.The trackwheel is located on the right side of the BlackBerry® device.Users can perform the following actions:Development Guide Trackball or trackpad9
  • • roll the trackwheel to move the cursor vertically• roll the trackwheel while pressing the Alt key to move the cursor horizontally• click the trackwheel to initiate an action or open the menuKeyboardUsers use the keyboard primarily to type text. Character keys send a character to the BlackBerry® device. A modifier key altersthe functionality of character keys. Modifier keys include the Shift key and the Alt key. When users press a modifier key, a typingmode indicator appears in the upper-right corner of the screen.On BlackBerry devices without a touch screen, users can also use the keyboard to move around a screen (for example, to movearound a map). However, navigation using the keyboard should always be an alternative to navigation using the trackwheel,trackball, or trackpad.BlackBerry devices have either a full keyboard or a reduced keyboard. On BlackBerry devices with a SurePress™ touch screen, inmost cases, the full keyboard appears in landscape view and the reduced keyboard appears in portrait view.Interaction methods on BlackBerry devicesBlackBerry device model Interaction methodBlackBerry® 7100 Series trackwheelBlackBerry® 8700 Series trackwheelBlackBerry® 8800 Series trackballBlackBerry® Bold™ 9000 smartphone trackballBlackBerry® Bold™ 9650 smartphoneBlackBerry® Bold™ 9700 smartphonetrackpadBlackBerry® Curve™ 8300 Series trackballBlackBerry® Curve™ 8500 Series trackpadBlackBerry® Curve™ 8900 smartphone trackballBlackBerry® Pearl™ 8100 Series trackballBlackBerry® Pearl™ Flip 8200 Series trackballBlackBerry® Storm™ 9500 Series touch screenBlackBerry® Tour™ 9630 smartphone trackballDevelopment Guide Keyboard10
  • Screens 3The main component of a BlackBerry® device UI is the Screen object.A BlackBerry device can have multiple screens open at the same time, but only one screen can be displayed at a time. TheBlackBerry® Java® Virtual Machine maintains an ordered set of Screen objects in a display stack. The screen on the top of thestack is the active screen that the BlackBerry device user sees. When a BlackBerry device application displays a screen, it pushesthe screen on the top of the stack. When a BlackBerry device application closes a screen, it pushes the screen off the top of thestack and displays the next screen on the stack, redrawing the screen as necessary.Each screen can appear only once on the display stack. The BlackBerry JVM throws a runtime exception if a screen that theBlackBerry device application pushes on the stack already exists. A BlackBerry device application must push a screen off thedisplay stack when the user finishes interacting with the screen so that the BlackBerry device application can use memoryefficiently. You should use only a few modal screens at one time, because each screen uses a separate thread.The UI APIs initialize simple Screen objects. After you create a screen, you can add fields and a menu, and display the screentotheuserbypushingitonthedisplaystack.YoucanchangetheBlackBerrydeviceUIandimplementnewfieldtypes,asrequired.You can also add custom navigation.The Screen class does not implement disambiguation, which is required for complex input methods, such as internationalkeyboards. For the integration of the different input methods, you can extend the Field class or one of its subclasses. Youshould not use Screen objects for typing text.Screen classesClass DescriptionScreen You can use the Screen class to create a screen and use a layout manager to layout the UI components on the screen. You can define a specific type of screen byusing the styles that the constants in the Field superclass define.FullScreen You can use the FullScreen class to create an empty screen to which you canadd UI components in a standard vertical layout. If you want to use another layoutstyle, such as horizontal or diagonal, you can use the Screen class instead and adda layout manager to it.MainScreen You can use the MainScreen class to create a screen with the following standardUI components:• default screen title, with a SeparatorField after the title• main scrollable section contained in a VerticalFieldManagerDevelopment Guide Screens11
  • Class Description• default menu with a Close menu item• default close action that closes the screen when the BlackBerry® device userclicks the Close menu item or presses the Escape keyYou should consider using a MainScreen object for the first screen of yourBlackBerry device application to maintain consistency with other BlackBerry deviceapplications.Manage a drawing areaThe Graphics object represents the entire drawing surface that is available to the BlackBerry® device application. To limit thisarea, divide it into XYRect objects. Each XYPoint represents a point on the screen, which is composed of an X co-ordinateand a Y co-ordinate.1. Import the following classes:• net.rim.device.api.ui.Graphics• net.rim.device.api.ui.XYRect• net.rim.device.api.ui.XYPoint2. Create XYPoint objects, to represent the top left and bottom right points of a rectangle. Create an XYRect object usingthe XYPoint objects, to create a rectangular clipping region.XYPoint bottomRight = new XYPoint(50, 50);XYPoint topLeft = new XYPoint(10, 10);XYRect rectangle = new XYRect(topLeft, bottomRight);3. Invoke Graphics.pushContext() to make drawing calls that specify that the region origin should not adjust thedrawing offset. Invoke Graphics.pushContext() to push the rectangular clipping region to the context stack. InvokeGraphics.drawRect() to draw a rectangle, and invoke Graphics.fillRect() to fill the rectangle. InvokeGraphics.popContext() to pop the current context off of the context stack.graphics.pushContext(rectangle, 0, 0);graphics.fillRect(10, 10, 30, 30);graphics.drawRect(15, 15, 30, 30);graphics.popContext();graphics.drawRect(15, 15, 30, 30);graphics.pushContext(rectangle, 0, 0);graphics.fillRect(10, 10, 30, 30);graphics.drawRect(15, 15, 30, 30);graphics.popContext();graphics.drawRect(15, 15, 30, 30);Development Guide Manage a drawing area12
  • 4. InvokepushRegion()andspecifythattheregionoriginshouldadjustthedrawingoffset.InvokeGraphics.drawRect() to draw a rectangle and invoke Graphics.fillRect() to fill a rectangle. Invoke Graphics.popContext() topop the current context off of the context stack.graphics.pushRegion(rectangle);graphics.fillRect(10, 10, 30, 30);graphics.drawRect(15, 15, 30, 30);graphics.popContext();5. Specify the portion of the Graphics object to push onto the stack.6. After you invoke pushContext() (or pushRegion()), provide the portion of the Graphics object to invert.graphics.pushContext(rectangle);graphics.invert(rectangle);graphics.popContext();7. Invoke translate(). The XYRect is translated from its origin of (1, 1) to an origin of (20, 20). After translation, thebottom portion of the XYRect object extends past the bounds of the graphics context and clips it.XYRect rectangle = new XYRect(1, 1, 100, 100);XYPoint newLocation = new XYPoint(20, 20);rectangle.translate(newLocation);Creating a screen transitionYou can create a screen transition to apply a visual effect that appears when your application opens or closes a screen on aBlackBerry® device. You can create the following types of screen transitions for your application by using thenet.rim.device.api.ui.TransitionContext class.Transition DescriptionTRANSITION_FADE Thistransitionrevealsorremovesascreenbyfadingitinorfadingitout.Thisscreentransition creates a fading visual effect by changing the opacity of the screen.TRANSITION_SLIDE This transition reveals or removes a screen by sliding it on or sliding it off the displayon the device. You can use attributes to specify that both the new screen and thecurrent screen slide, to create an effect where both screens appear to move, or thatthe new screen slides over the current screen.TRANSITION_WIPE This transition reveals or removes a screen by simulating wiping on or wiping offthe display on the device.TRANSITION_ZOOM This transition reveals or removes a screen by zooming it in or zooming it out of thedisplay on the device.TRANSITION_NONE No transition occurs.Development Guide Creating a screen transition13
  • Each type of screen transition has attributes that you can use to customize the visual effects of the screen transition. For example,you can customize a sliding effect so that a screen slides from the bottom of the display on the device to the top of the display.If you do not customize the screen transition, the application uses the default attributes. For more information on the defaultattributes, see the API reference for the BlackBerry® Java® Development Environment.After you create a screen transition, you must register it within your application by invokingUiEngineInstance.setTransition() and specify the outgoing screen to remove and the incoming screen to reveal,the events that cause the transition to occur, and the transition to display.To download a sample application that demonstrates how to use screen transitions, visit www.blackberry.com/go/screentransitionssample. For more information about screen transitions, see the API reference for the BlackBerry JavaDevelopment Environment.Note: The theme on the BlackBerry device controls the visual effects that display when a user opens an application. For moreinformation, see the BlackBerry Theme Studio User Guide.Code sample: Creating a screen transitionThe following code sample illustrates a slide transition and a fade transition. When the user opens the application, the first screenappears on the BlackBerry® device and displays a button. When the user clicks the button, a second screen slides onto the displayfrom the right. The second screen automatically fades off of the display after two seconds.import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;import net.rim.device.api.ui.decor.*;public class ScreenTransitionSample extends UiApplication implementsFieldChangeListener {private Screen _secondaryScreen;private Runnable _popRunnable;public static void main(String[] args) {ScreenTransitionSample theApp = new ScreenTransitionSample ();theApp.enterEventDispatcher();}public ScreenTransitionSample () {_secondaryScreen = new FullScreen();_secondaryScreen.setBackground(BackgroundFactory.createSolidBackground(Color.LIGHTBLUE) );LabelField labelField = new LabelField("The screen closes automatically intwo seconds by using a fade transition");_secondaryScreen.add(labelField);TransitionContext transition = newTransitionContext(TransitionContext.TRANSITION_SLIDE);Development Guide Creating a screen transition14
  • transition.setIntAttribute(TransitionContext.ATTR_DURATION, 500);transition.setIntAttribute(TransitionContext.ATTR_DIRECTION,TransitionContext.DIRECTION_RIGHT);transition.setIntAttribute(TransitionContext.ATTR_STYLE,TransitionContext.STYLE_PUSH);UiEngineInstance engine = Ui.getUiEngineInstance();engine.setTransition(null, _secondaryScreen, UiEngineInstance.TRIGGER_PUSH,transition);transition = new TransitionContext(TransitionContext.TRANSITION_FADE);transition.setIntAttribute(TransitionContext.ATTR_DURATION, 500);transition.setIntAttribute(TransitionContext.ATTR_KIND,TransitionContext.KIND_OUT);engine.setTransition(_secondaryScreen, null, UiEngineInstance.TRIGGER_POP,transition);MainScreen baseScreen = new MainScreen();baseScreen.setTitle("Screen Transition Sample");ButtonField buttonField = new ButtonField("View Transition",ButtonField.CONSUME_CLICK) ;buttonField.setChangeListener(this);baseScreen.add(buttonField);pushScreen(baseScreen);_popRunnable = new Runnable() {public void run() {popScreen(_secondaryScreen);}};}public void fieldChanged(Field field, int context){pushScreen(_secondaryScreen);invokeLater(_popRunnable, 2000, false);}}Specifying the orientation and direction of the screenIn touch screen applications, you can take into account both the orientation and the direction of the screen. Orientation relatesto the screens aspect ratio. Direction relates to the drawing area of the screen.OrientationDevelopment Guide Specifying the orientation and direction of the screen15
  • The user of a BlackBerry® device with a touch screen can change the orientation of the screen by rotating the device. If a userholds the BlackBerry device with the BlackBerry logo at the top, the screen is in portrait orientation. If the user rotates the device90 degrees to the left or right, the screen is in landscape orientation.You can use the net.rim.device.api.system.Display class to retrieve the orientation of the screen. The Displayclasscontainstheconstantsthatcorrespondtotheorientationsthatthedevicewithatouchscreencanusetodisplayinformation.For example, the portrait, landscape, and square orientations correspond to the Display.ORIENTATION_PORTRAIT,Display.ORIENTATION_LANDSCAPE, and Display.ORIENTATION_SQUARE constants.To retrieve the orientation of the screen, you can invoke the Display.getOrientation() method. This method returns aninteger that corresponds to one of the orientations that the BlackBerry device can use.To detect orientation changes, you can override Screen.sublayout(). In that method, invoke super.sublayout() andwatch for changes in the width and height values.DirectionA BlackBerry device with a touch screen can display information on the screen in different directions. Direction refers to the topof the drawing area of the screen, which is relative to the location of the BlackBerry logo. The direction is north when the top ofthe drawable area is the screen side closest to the BlackBerry logo; the direction is west when the top of the drawable area is tothe left of the BlackBerry logo; the direction is east when the top of the drawable area is to the right of the BlackBerry logo.You can use the net.rim.device.api.system.Display class, the net.rim.device.api.ui.Ui class, and thenet.rim.device.api.ui.UiEngineInstance class to control the direction that the BlackBerry device uses to displayinformation on the screen. The Display class contains constants that correspond to the directions that the device can use todisplay information. For example, the north, west, and east directions correspond to the Display.DIRECTION_NORTH,Display.DIRECTION_WEST, and Display.DIRECTION_EAST constants.You can create an object of the net.rim.device.api.ui.Ui class and invoke Ui.getUiEngineInstance() toretrieve an object of the UiEngineInstance class. Invoking UiEngineInstance.setAcceptableDirections()with one of the constants that correspond to directions from the Display class sets the direction that the BlackBerry devicecan use to display information.Code sample: Retrieving screen orientationswitch(Display.getOrientation()){case Display.ORIENTATION_LANDSCAPE:Dialog.alert("Screen orientation is landscape"); break;case Display.ORIENTATION_PORTRAIT:Dialog.alert("Screen orientation is portrait"); break;case Display.ORIENTATION_SQUARE:Dialog.alert("Screen orientation is square"); break;default:Dialog.alert("Screen orientation is not known"); break;}Code sample: Forcing portrait view in a BlackBerry API applicationDevelopment Guide Specifying the orientation and direction of the screen16
  • // Use code like this before invoking UiApplication.pushScreen()int direction = Display.DIRECTION_NORTH;Ui.getUiEngineInstance().setAcceptableDirections(direction);Code sample: Forcing landscape view in a MIDlet application// Use code like this before invoking Display.setCurrent() in the MIDlet constructorDirectionControl dc =(DirectionControl) ((Controllable) Display.getDisplay(this)).getControl("net.rim.device.api.lcdui.control.DirectionControl");int directions = DirectionControl.DIRECTION_EAST | DirectionControl.DIRECTION_WEST;dc.setAcceptableScreenDirections(directions);Retrieve the orientation of the touch screen1. Import the net.rim.device.api.system.Display class.2. Invoke net.rim.device.api.system.Display.getOrientation().int orientation = Display.getOrientation();Restrict the touch screen direction1. Import the following classes:• net.rim.device.api.ui.Ui• net.rim.device.api.ui.UiEngineInstance2. Invoke net.rim.device.api.ui.Ui.getUiEngineInstance().UiEngineInstance _ue;_ue = Ui.getUiEngineInstance();3. Invoke net.rim.device.api.ui.UiEngineInstance.setAcceptableDirections(byte flags) andpass the argument for the direction of the Screen._ue.setAcceptableDirections(Display.DIRECTION_WEST);Receive notification when the size of the drawable area of the touch screen changes1. Import the following classes:• javax.microedition.lcdui.Canvas• net.rim.device.api.ui.component.Dialog2. Extend javax.microedition.lcdui.Canvas.3. Override Canvas.sizeChanged(int,int).Development Guide Specifying the orientation and direction of the screen17
  • protected void sizeChanged(int w, int h) {Dialog.alert("The size of the Canvas has changed");}Development Guide Specifying the orientation and direction of the screen18
  • Accelerometer 4A BlackBerry® device with a touch screen includes an accelerometer, which is designed to sense the orientation and accelerationoftheBlackBerrydevice.WhenaBlackBerrydeviceusermovestheBlackBerrydevice,theaccelerometercansensethemovementin 3-D space along the x, y, and z axis. A device user can change the orientation of the device which can change the displaydirection of a screen for a BlackBerry device application between portrait and landscape.You can use the Accelerometer APIs in the net.rim.device.api.system package to respond to the orientation andacceleration of a BlackBerry device. For example, you can manipulate a game application to change the direction and speed ofa moving object on the screen as a user moves and rotates the BlackBerry device at different speeds.To download a sample application that demonstrates how to use the accelerometer, visit www.blackberry.com/go/accelerometersample. For more information about the sample application, visit www.blackberry.com/go/devguides to read theAccelerometer Sample Application Overview.Types of accelerometer dataA BlackBerry® device application can retrieve data from the accelerometer.Data type Descriptionorientation The orientation of the BlackBerry device with respect to the ground.acceleration The acceleration of the rotation of the BlackBerry device.For more information about types of data from the accelerometer, see the API reference for the BlackBerry® Java® DevelopmentEnvironment.Retrieving accelerometer dataThe accelerometer is designed to track the direction and speed of the movement along an x, y, and z axis when a BlackBerry®device user moves the BlackBerry device. The x axis is parallel to the width of the BlackBerry device. The y axis is parallel to thelength of the BlackBerry device. The z axis is parallel to the depth (front to back) of the BlackBerry device. For more informationabout the x, y, and z axes of the accelerometer, see the net.rim.device.api.system.AccelerometerSensor classin the API reference for the BlackBerry® Java® Development Environment.YoucanenableaBlackBerrydeviceapplicationtoreacttotheaccelerationoftheBlackBerrydevicethatincludesanaccelerometer.For example, a BlackBerry device user could move the BlackBerry device to control the direction and speed of an object thatmoves through a maze in a game application.Development Guide Accelerometer19
  • You can use the Accelerometer APIs, in the net.rim.device.api.system package, to react to the acceleration of theBlackBerry device. You must first determine whether the BlackBerry device supports an accelerometer by invokingnet.rim.device.api.system.AccelerometerSensor.isSupported(). If the method returns the value true,the BlackBerry device supports an accelerometer.You can use the AccelerometerData class to identify the direction the user moves the BlackBerry device. InvokingAccelerometerData.getOrientation() returns one of the AccelerometerSensor class constants thatcorrespond to the direction of the BlackBerry device. For example, if AccelerometerData.getOrientation() returnsa value equal to AccelerometerSensor.ORIENTATION_LEFT_UP, the left side of the BlackBerry device is in an upwarddirection.You can use the AccelerometerSensor class to retrieve acceleration data from the BlackBerry device. InvokingAccelerometerSensor.openRawDataChannel() returns an object of thenet.rim.device.api.system.AccelerometerSensor.Channel class. TheAccelerometerSensor.Channel class allows you to open a connection to the accelerometer. You can retrieve data fromthe accelerometer by invoking AccelerometerSensor.Channel.getLastAccelerationData().Maintaining a connection to the accelerometer uses power from the BlackBerry device battery. When the BlackBerry deviceapplication no longer needs to retrieve data from the accelerometer, you should invokeAccelerometerSensor.Channel.close() to close the connection.Code sample: Retrieving data from the accelerometershort[] xyz = new short[3];while( running ) {channel.getLastAccelerationData(xyz);}channel.close();Retrieve accelerometer data at specific intervalsIf a BlackBerry® device application opens a channel to the accelerometer when the application is in the foreground, when theapplication is in the background, the channel pauses and the accelerometer is not queried. If a BlackBerry device applicationinvokes AccelerometerSensor.Channel. getLastAccelerationData(short[]) at close intervals or when theBlackBerry device is not in motion, the method might return duplicate values.1. Import the following classes:• net.rim.device.api.system.AccelerometerSensor.Channel;• net.rim.device.api.system.AccelerometerSensor;2. Openachanneltotheaccelerometer.Whileachannelisopen,theBlackBerrydeviceapplicationwillquerytheaccelerometerfor information.Channel rawDataChannel = AccelerometerSensor.openRawDataChannel( Application.getApplication() );Development Guide Retrieve accelerometer data at specific intervals20
  • 3. Create an array to store the accelerometer data.short[] xyz = new short[ 3 ];4. Create a thread.while( running ) {5. Invoke Channel.getLastAccelerationData(short[]) to retrieve data from the accelerometer.rawDataChannel.getLastAccelerationData( xyz );6. Invoke Thread.sleep() to specify the interval between queries to the accelerometer, in milliseconds.Thread.sleep( 500 );7. Invoke Channel.close() to close the channel to the accelerometer.rawDataChannel.close();Query the accelerometer when the application is in the foreground1. Import the following classes:• net.rim.device.api.system.AccelerometerChannelConfig• net.rim.device.api.system.AccelerometerSensor.Channel2. Open a channel to retrieve acceleration data from the accelerometer.Channel channel = AccelerometerSensor.openRawAccelerationChannel( Application.getApplication());3. Invoke Thread.sleep() to specify the interval between queries to the accelerometer, in milliseconds.short[] xyz = new short[ 3 ];while( running ) {channel.getLastAccelerationData( xyz );Thread.sleep( 500 );}4. Invoke Channel.close() to close the channel to the accelerometer.channel.close();Query the accelerometer when the application is in the background1. Import the following classes:• net.rim.device.api.system.AccelerometerChannelConfig;• net.rim.device.api.system.AccelerometerSensor.Channel;2. Create a configuration for a channel to the accelerometer.Development Guide Query the accelerometer when the application is in the foreground21
  • AccelerometerChannelConfig channelConfig = new AccelerometerChannelConfig( AccelerometerChannelConfig.TYPE_RAW );3. Invoke AccelerometerChannelConfig.setBackgroundMode(Boolean), to specify support for an applicationthat is in the background.channelConfig.setBackgroundMode( true );4. Invoke AccelerometerSensor.openChannel(), to open a background channel to the accelerometer.Channel channel = AccelerometerSensor.openChannel( Application.getApplication(),channelConfig );5. Invoke Thread.sleep() to specify the interval between queries to the accelerometer, in milliseconds.short[] xyz = new short[ 3 ];while( running ) {channel.getLastAccelerationData( xyz );Thread.sleep( 500 );}6. Invoke Channel.close() to close the channel to the accelerometer.channel.close();Store accelerometer readings in a buffer1. Import the following classes:• net.rim.device.api.system.AccelerometerChannelConfig;• net.rim.device.api.system.AccelerometerSensor.Channel;2. Create a configuration for a channel to the accelerometer.AccelerometerChannelConfig channelConfig = new AccelerometerChannelConfig( AccelerometerChannelConfig.TYPE_RAW );3. Invoke AccelerometerChannelConfig.setSamplesCount(), to specify the number of acceleration readings tostore in the buffer. Each element in the buffer contains acceleration readings for the x, y, and z axes and data on when thereading took place.channelConfig.setSamplesCount( 500 );4. Invoke AccelerometerSensor.openChannel() to open a channel to the accelerometer.Channel bufferedChannel = AccelerometerSensor.openChannel( Application.getApplication(), channelConfig );Development Guide Store accelerometer readings in a buffer22
  • Retrieve accelerometer readings from a buffer1. Import the following classes:• net.rim.device.api.system.AccelerometerData;• net.rim.device.api.system.AccelerometerSensor.Channel;2. Query the buffer for accelerometer data.AccelerometerData accData = bufferedChannel.getAccelerometerData();3. Invoke AccelerometerData.getNewBatchLength(), to get the number of readings retrieved since the last query.int newBatchSize = accData.getNewBatchLength();4. Invoke AccelerometerData.getXAccHistory(), AccelerometerData.getYAccHistory(), andAccelerometerData.getZAccHistory() to retrieve accelerometer data from the buffer for each axis.short[] xAccel = accData.getXAccHistory();short[] yAccel = accData.getYAccHistory();short[] zAccel = accData.getZAccHistory();Get the time a reading was taken from the accelerometer1. Import the net.rim.device.api.system.AccelerometerData class.2. Query the buffer for accelerometer data.AccelerometerData accData;accData = bufferedChannel.getAccelerometerData();3. Invoke AccelerometerData.getSampleTsHistory().long[] queryTimestamps = accData.getSampleTsHistory();Development Guide Retrieve accelerometer readings from a buffer23
  • Events 5Respond to navigation eventsYou can use the Screen navigation methods to create a BlackBerry® device application. If your existing BlackBerry deviceapplication implements the TrackwheelListener interface, update your BlackBerry device application to use theScreen navigation methods.1. Import the net.rim.device.api.ui.Screen class.2. Manage navigation events by extending the net.rim.device.api.ui.Screen class (or one of its subclasses) andoverriding the following navigation methods:navigationClick(int status, int time)navigationUnclick(int status, int time)navigationMovement(int dx, int dy, int status, int time)Determine the type of input method1. Import one or more of the following classes:• net.rim.device.api.ui.Screen• net.rim.device.api.ui.Field2. Import the net.rim.device.api.system.KeypadListener interface.3. Implement the net.rim.device.api.system.KeypadListener interface.4. Extend the Screen class, the Field class, or both.5. In your implementation of one of the navigationClick, navigationUnclick, or navigationMovementmethods,performabitwiseANDoperationonthestatus parametertoyieldmoreinformationabouttheevent.Implementthe navigationClick(intstatus,inttime) method to determine if the trackwheel or a four way navigationinput device (for example, a trackball) triggers an event.public boolean navigationClick(int status, int time) {if ((status & KeypadListener.STATUS_TRACKWHEEL) ==KeypadListener.STATUS_TRACKWHEEL) {//Input came from the trackwheel} else if ((status & KeypadListener.STATUS_FOUR_WAY) ==KeypadListener.STATUS_FOUR_WAY) {//Input came from a four way navigation input device}return super.navigationClick(status, time);}For more information about status modifiers for the net.rim.device.api.system.KeypadListener class, seethe API reference for the BlackBerry® Java® Development Environment.Development Guide Events24
  • Touch screen interaction modelsBlackBerry® devices with a touch screen and a trackpad use a forceless click interaction model, where a BlackBerry device usertaps the screen or uses the trackpad to perform an action. This model differs from BlackBerry devices with a SurePress™ touchscreen, where the user clicks (or presses) the screen to perform an action.On both types of devices, when the user touches the screen, a TouchEvent.DOWN event occurs.On devices with a SurePress touch screen, when the user applies pressure and clicks the screen, a TouchEvent.CLICK eventoccurs. When the pressure is lessened, a TouchEvent.UNCLICK event occurs. Typically, actions (such as invoking an actionbased on a button) occur on the TouchEvent.UNCLICK event. When the user releases the screen completely, aTouchEvent.UP event occurs.On devices with a touch screen that supports forceless clicks, there is no physical clicking and unclicking. Instead, actions areexpected to occur when the user taps the screen. A tap is a TouchEvent.DOWN event followed quickly by aTouchEvent.UP event. This combination of touch events is referred to as a gesture, and therefore a TouchGesture occurs.In the case of a tap, a TouchGesture.TAP event occurs (along with the TouchEvent.DOWN and TouchEvent.UP event).For greater compatibility between the two types of touch screen interaction models, on devices that support forceless clicks, theTouchEvent.CLICK event and TouchEvent.UNCLICK event occur after the TouchGesture.TAP event, so you caninvoke an action on the TouchEvent.UNCLICK event on all touch screen devices, whether the device has a SurePress touchscreen or not.User action Devices that support a forceless click Devices with a SurePress touch screenTouch the screen. TouchEvent.DOWN TouchEvent.DOWNTouch and hold a finger onan item.TouchGesture.HOVER TouchGesture.HOVERClick the screen. — TouchEvent.CLICKClick and hold the screen. — TouchEvent.CLICK_REPEATRelease the screen. — TouchEvent.UNCLICKRemove a finger from thescreen.TouchEvent.UP TouchEvent.UPTap the screen. TouchEvent.DOWNTouchGesture.TAPTouchEvent.CLICKTouchEvent.UNCLICKTouchEvent.DOWNTouchGesture.TAPTouchEvent.UPDevelopment Guide Touch screen interaction models25
  • User action Devices that support a forceless click Devices with a SurePress touch screenTouchEvent.UPYou can determine whether a device with a touch screen supports forceless clicks by invokingDeviceCapability.isTouchClickSupported(). If the device supports forceless clicks, the method returns false.If the device has a SurePress touch screen, the method returns true.Responding to touch screen eventsBlackBerry® device users can perform the same actions on a device with a touch screen as they can on a BlackBerry device witha trackball. For example, BlackBerry device users can use the touch screen to open a menu, scroll through a list of options, andselect an option.If you use a version of the BlackBerry® Java® Development Environment earlier than version 4.7 to create a BlackBerry deviceapplication, you can alter the .jad file of the application to enable the application to respond when a BlackBerry device usertouches the touch screen. In the .jad file, you would set the RIM-TouchCompatibilityMode option to false.If you use BlackBerry JDE version 4.7 or later to create a BlackBerry device application, you can enable the application to identifythe action the BlackBerry device user performs on the touch screen by extending the net.rim.device.api.ui.Screenclass, the net.rim.device.api.ui.Field class, or one of the subclasses of the Field class and overriding thetouchEvent() method. Within the touchEvent() method, compare the value that TouchEvent.getEvent() returnsto the constants from the net.rim.device.api.ui.TouchEvent class and thenet.rim.device.api.ui.TouchGesture class.The TouchEvent class contains the constants that represent the different actions that a user can perform on the touch screen.For example, the click, touch, and move actions correspond to the TouchEvent.CLICK, TouchEvent.DOWN, andTouchEvent.MOVE constants.The TouchGesture class contains the constants that represent the different gestures that a user can perform on a touchscreen. For example, the tap and swipe gestures correspond to the TouchGesture.TAP and TouchGesture.SWIPEconstants.Code sample: Identifying the action a user performs on the touch screenThe following code sample uses a switch statement to identify the action.protected boolean touchEvent(TouchEvent message) {switch(message.getEvent()) {case TouchEvent.CLICK:Dialog.alert("A click action occurred");return true;case TouchEvent.DOWN:Dialog.alert("A down action occurred");Development Guide Responding to touch screen events26
  • return true;case TouchEvent.MOVE:Dialog.alert("A move action occurred");return true;}return false;}Respond to system events while the user touches the screen1. Import the following classes:• net.rim.device.api.ui.TouchEvent• net.rim.device.api.ui.Field• net.rim.device.api.ui.Manager• net.rim.device.api.ui.Screen• net.rim.device.api.ui.component.Dialog2. Create a class that extends the Manager class, the Screen class, the Field class, or one of the Field subclasses.public class newButtonField extends ButtonField {3. In your implementation of the touchEvent(TouchEventmessage) method, invoke TouchEvent.getEvent().4. Check if the value that TouchEvent.getEvent() returns is equal to TouchEvent.CANCEL.protected boolean touchEvent(TouchEvent message) {switch(message.getEvent()) {case TouchEvent.CANCEL:Dialog.alert("System event occurred while processing touch events");return true;}return false;}Respond to a user sliding a finger up quickly on the screen1. Import the following classes:• net.rim.device.api.ui.TouchEvent• net.rim.device.api.ui.TouchGesture• net.rim.device.api.ui.Field• net.rim.device.api.ui.Manager• net.rim.device.api.ui.Screen• net.rim.device.api.ui.component.Dialog2. Create a class that extends the Manager class, the Screen class, the Field class, or one of the Field subclasses.Development Guide Responding to touch screen events27
  • public class newButtonField extends ButtonField {3. In your implementation of the touchEvent(TouchEventmessage) method, invoke TouchEvent.getEvent().4. Check if the value that TouchGesture.getSwipeDirection() returns is equal toTouchGesture.SWIPE_NORTH.protected boolean touchEvent(TouchEvent message) {switch(message.getEvent()) {case TouchEvent.GESTURE:TouchGesture gesture = message.getGesture();switch(gesture.getEvent()) {case TouchGesture.SWIPE:if(gesture.getSwipeDirection() == TouchGesture.SWIPE_NORTH) {Dialog.alert("Upward swipe occurred");return true;}}return false;}}Respond to a user sliding a finger down quickly on the screen1. Import the following classes:• net.rim.device.api.ui.TouchEvent• net.rim.device.api.ui.TouchGesture• net.rim.device.api.ui.Field• net.rim.device.api.ui.Manager• net.rim.device.api.ui.Screen• net.rim.device.api.ui.component.Dialog2. Create a class that extends the Manager class, the Screen class, the Field class, or one of the Field subclasses.public class newButtonField extends ButtonField {3. In your implementation of the touchEvent(TouchEventmessage) method, invoke TouchEvent.getEvent().4. Check if the value that TouchGesture.getSwipeDirection() returns is equal toTouchGesture.SWIPE_SOUTH.protected boolean touchEvent(TouchEvent message) {switch(message.getEvent()) {case TouchEvent.GESTURE:TouchGesture gesture = message.getGesture();switch(gesture.getEvent()) {case TouchGesture.SWIPE:if(gesture.getSwipeDirection() == TouchGesture.SWIPE_SOUTH) {Dialog.alert("Downward swipe occurred");return true;Development Guide Responding to touch screen events28
  • }}return false;}}Respond to a user sliding a finger to the left quickly on the screen1. Import the following classes:• net.rim.device.api.ui.TouchEvent• net.rim.device.api.ui.TouchGesture• net.rim.device.api.ui.Field• net.rim.device.api.ui.Manager• net.rim.device.api.ui.Screen• net.rim.device.api.ui.component.Dialog2. Create a class that extends the Manager class, the Screen class, the Field class, or one of the Field subclasses.public class newButtonField extends ButtonField {3. In your implementation of the touchEvent(TouchEventmessage) method, invoke TouchEvent.getEvent().4. CheckifthevaluethatTouchGesture.getSwipeDirection()returnsisequaltoTouchGesture.SWIPE_EAST.protected boolean touchEvent(TouchEvent message) {switch(message.getEvent()) {case TouchEvent.GESTURE:TouchGesture gesture = message.getGesture();switch(gesture.getEvent()) {case TouchGesture.SWIPE:if(gesture.getSwipeDirection() == TouchGesture.SWIPE_EAST) {Dialog.alert("Eastward swipe occurred");return true;}}return false;}}Respond to a user sliding a finger to the right quickly on the screen1. Import the following classes:• net.rim.device.api.ui.TouchEvent• net.rim.device.api.ui.TouchGesture• net.rim.device.api.ui.Field• net.rim.device.api.ui.Manager• net.rim.device.api.ui.ScreenDevelopment Guide Responding to touch screen events29
  • • net.rim.device.api.ui.component.Dialog2. Create a class that extends the Manager class, the Screen class, the Field class, or one of the Field subclasses.public class newButtonField extends ButtonField {3. In your implementation of the touchEvent(TouchEventmessage) method, invoke TouchEvent.getEvent().4. CheckifthevaluethatTouchGesture.getSwipeDirection()returnsisequaltoTouchGesture.SWIPE_WEST.protected boolean touchEvent(TouchEvent message) {switch(message.getEvent()) {case TouchEvent.GESTURE:TouchGesture gesture = message.getGesture();switch(gesture.getEvent()) {case TouchGesture.SWIPE:if(gesture.getSwipeDirection() == TouchGesture.SWIPE_WEST) {Dialog.alert("Westward swipe occurred");return true;}}return false;}}Respond to a user clicking the screen1. Import the following classes:• net.rim.device.api.ui.TouchEvent• net.rim.device.api.ui.Field• net.rim.device.api.ui.Manager• net.rim.device.api.ui.Screen• net.rim.device.api.ui.component.Dialog2. Create a class that extends the Manager class, the Screen class, the Field class, or one of the Field subclasses.public class newButtonField extends ButtonField {3. In your implementation of the touchEvent(TouchEventmessage) method, invoke TouchEvent.getEvent().4. Check if the value that TouchEvent.getEvent() returns is equal to TouchEvent.CLICK.protected boolean touchEvent(TouchEvent message) {switch(message.getEvent()) {case TouchEvent.CLICK:Dialog.alert("CLICK occurred");return true;}return false;}Development Guide Responding to touch screen events30
  • Respond to a user touching the screen twice quickly1. Import the following classes:• net.rim.device.api.ui.TouchEvent• net.rim.device.api.ui.TouchGesture• net.rim.device.api.ui.Field• net.rim.device.api.ui.Manager• net.rim.device.api.ui.Screen• net.rim.device.api.ui.component.Dialog2. Create a class that extends the Manager class, the Screen class, the Field class, or one of the Field subclasses.public class newButtonField extends ButtonField {3. In your implementation of the touchEvent(TouchEventmessage) method, check for the occurrence of aTouchGesture.TAP event and that TouchGesture.getTapCount returns 2.protected boolean touchEvent(TouchEvent message) {switch(message.getEvent()) {case TouchEvent.GESTURE:TouchGesture gesture = message.getGesture();switch(gesture.getEvent()) {case TouchGesture.TAP:if(gesture.getTapCount() == 2) {Dialog.alert("Double tap occurred");return true;}}}return false;}Respond to a user touching and dragging an item on the screen1. Import the following classes:• net.rim.device.api.ui.TouchEvent• net.rim.device.api.ui.Field• net.rim.device.api.ui.Manager• net.rim.device.api.ui.Screen• net.rim.device.api.ui.component.Dialog2. Create a class that extends the Manager class, the Screen class, the Field class, or one of the Field subclasses.public class newButtonField extends ButtonField {3. In your implementation of the touchEvent(TouchEventmessage) method, invoke TouchEvent.getEvent().Development Guide Responding to touch screen events31
  • 4. Check if the value that TouchEvent.getEvent() returns is equal to TouchEvent.MOVE.protected boolean touchEvent(TouchEvent message) {switch(message.getEvent()) {case TouchEvent.MOVE:Dialog.alert("Move event occurred");return true;}return false;}Respond to a user touching the screen lightly1. Import the following classes:• net.rim.device.api.ui.TouchEvent• net.rim.device.api.ui.TouchGesture• net.rim.device.api.ui.Field• net.rim.device.api.ui.Manager• net.rim.device.api.ui.Screen• net.rim.device.api.ui.component.Dialog2. Create a class that extends the Manager class, the Screen class, the Field class, or one of the Field subclasses.public class newButtonField extends ButtonField {3. In your implementation of the touchEvent(TouchEventmessage) method, invoke TouchEvent.getEvent().4. Check if the value that TouchEvent.getEvent() returns is equal to TouchEvent.DOWN.protected boolean touchEvent(TouchEvent message) {switch(message.getEvent()) {case TouchEvent.DOWN:Dialog.alert("Touch occurred");return true;}return false;}Respond to a scroll action1. Import the following classes:• net.rim.device.api.ui.TouchEvent• net.rim.device.api.ui.TouchGesture• net.rim.device.api.ui.Field• net.rim.device.api.ui.Manager• net.rim.device.api.ui.ScreenDevelopment Guide Responding to touch screen events32
  • 2. Create a class that extends the Manager class.public class newManager extends Manager {3. In your implementation of the touchEvent(TouchEventmessage) method, check if the valueTouchEvent.getEvent() returns is equal to TouchEvent.MOVE.protected boolean touchEvent(TouchEvent message) {switch(message.getEvent()) {case TouchEvent.MOVE:return true;}return false;}Respond to a user touching the screen in two locations at the same time1. Import the following classes:• net.rim.device.api.ui.TouchEvent• net.rim.device.api.ui.Field• net.rim.device.api.ui.Manager• net.rim.device.api.ui.Screen• net.rim.device.api.ui.component.Dialog2. Create a class that extends the Manager class, the Screen class, the Field class, or one of the Field subclasses.public class newButtonField extends ButtonField {3. InyourimplementationofthetouchEvent(TouchEventmessage)method,checkifthefollowingmethodinvocationsreturn values greater than zero: TouchEvent.getX(1), TouchEvent.getY(1), TouchEvent.getX(2),TouchEvent.getY(2).protected boolean touchEvent(TouchEvent message) {switch(message.getEvent()) {case TouchEvent.MOVE:if(message.getX(1) > 0 && message.getY(1) > 0) {Dialog.alert("First finger touched/moved");}if(message.getX(2) > 0 && message.getY(2) > 0) {Dialog.alert("Second finger touched/moved");}return true;}return false;}Development Guide33
  • Pinch gesturesBlackBerry® devices with a touch screen support pinch gestures. Pinch gestures typically zoom in and out of an object on thescreen.A pinch begins when two touch points are detected on the touch screen. A pinch’s focal point is defined as the midpoint betweenthe two initial touch points.• When two touch points are detected, a TouchGesture.PINCH_BEGIN event occurs. The coordinate points of the focalpointofthepinchgesturearestoredasTouchEvent.getX(1) andTouchEvent.getY(1).Youcanaccesstheinitialzoom value by invoking TouchGesture.getPinchMagnitude().• As the user moves one or both touch points, a series of TouchGesture.PINCH_UPDATE events occur. You can accessthe zoom values during the pinch by invoking TouchGesture.getPinchMagnitude().• When the user completes the gesture, a TouchGesture.PINCH_END event occurs. You can access the final zoom valueby invoking TouchGesture.getPinchMagnitude().Code sample: Retrieving information about a pinch gestureThis sample demonstrates how to handle a pinch gesture in a screens touchEvent() method.protected boolean touchEvent(TouchEvent message){switch(message.getEvent()){case TouchEvent.GESTURE:TouchGesture gesture = message.getGesture();switch(gesture.getEvent()){case TouchGesture.PINCH_END:Dialog.alert("Focal point: " + message.getX(1)+ ", " + message.getY(1)+ "nFinal zoom value: " + gesture.getPinchMagnitude());return true;}}return false;}Enable pinch gesturesBy default, pinch gestures are not enabled on a screen in a BlackBerry® device application. You must set a screen property toenable the generation of pinch gestures on a screen.1. Import the required classes and interfaces.Development Guide Pinch gestures34
  • import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;import net.rim.device.api.ui.input.*;2. In your screen object, create an InputSettings object to populate with touch screen properties.InputSettings ts = TouchscreenSettings.createEmptySet();3. Set the TouchscreenSettings.DETECT_PINCH property to 1.ts.set(TouchscreenSettings.DETECT_PINCH, 1);4. Invoke Screen.addInputSettings() to add the input settings to the screen.addInputSettings(ts);You can change the value of the TouchscreenSettings.DETECT_PINCH property at any time, not just when you createthe screen.Code sampleThis sample demonstrates how to enable pinch gestures in a screens constructor.public MyScreen(){setTitle("Sample Screen");InputSettings ts = TouchscreenSettings.createEmptySet();ts.set(TouchscreenSettings.DETECT_PINCH, 1);addInputSettings(ts);...}Swipe gestures with trackpadsSimilar to BlackBerry® devices with a touch screen, devices with a trackpad support swipe gestures that BlackBerry device usersmake on the trackpad.A TouchEvent object with the event type TouchGesture.NAVIGATION_SWIPE is generated when the user swipes acrossthe trackpad. You can retrieve information about the trackpad swipe by using the following methods:• TouchGesture.getSwipeAngle()• TouchGesture.getSwipeDirection()• TouchGesture.getSwipeContentAngle()• TouchGesture.getSwipeContentDirection()• TouchGesture.getSwipeMagnitude()Development Guide Swipe gestures with trackpads35
  • Code sample: Retrieving information about a trackpad swipeThis sample demonstrates how to handle a trackpad swipe in a screens touchEvent() method.protected boolean touchEvent(TouchEvent message){switch(message.getEvent()){case TouchEvent.GESTURE:TouchGesture gesture = message.getGesture();switch(gesture.getEvent()){case TouchGesture.NAVIGATION_SWIPE:Dialog.alert("Swipe direction: " + gesture.getSwipeDirection()+ ", "+ "nMagnitude: " + gesture.getSwipeMagnitude());return true;}}return false;}Enable swipe gestures that users make on the trackpadBy default, swipe gestures that BlackBerry® device users make on the trackpad are not enabled on a screen. You must set anavigation property to enable the generation of trackpad swipe gestures on a screen.1. Import the required classes and interfaces.import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;import net.rim.device.api.ui.input.*;2. In your screen object, create an InputSettings object to populate with navigation properties.InputSettings nd = NavigationDeviceSettings.createEmptySet();3. Set the NavigationDeviceSettings.DETECT_SWIPE property to 1.nd.set(NavigationDeviceSettings.DETECT_SWIPE, 1);4. Invoke Screen.addInputSettings() to add the input settings to the screen.addInputSettings(nd);You can change the value of the NavigationDeviceSettings.DETECT_SWIPE property at any time, not just when youcreate the screen.Code sampleDevelopment Guide Swipe gestures with trackpads36
  • This sample demonstrates how to enable trackpad swipe gestures in a screens constructor.public MyScreen(){setTitle("Sample Screen");InputSettings nd = NavigationDeviceSettings.createEmptySet();nd.set(NavigationDeviceSettings.DETECT_SWIPE, 1);addInputSettings(nd);...}Event injectionYoucangenerateUIeventsprogrammaticallybyusingtheEventInjector classanditsinnerclasses.OnBlackBerry®devicesthat run BlackBerry® Device Software version 5.0 or later and have touch screens, you can inject touch events such as swipesand taps. You can use one of the EventInjector inner classes to model an event and you can use the invokeEvent()method to inject the event. The event is sent to the application that is currently selected and ready to accept input.You can use event injection to automate testing. You can also use event injection to provide a way for peripherals to interactwithaBlackBerrydevice.Youcanalsouseitinaccessibleapplicationssuchasspeech-to-textconverters.Forasampleapplicationthat demonstrates event injection, visit www.blackberry.com/go/toucheventinjectorsampleapp to download the Touch EventInjector sample application. For more information about the sample application, visit www.blackberry.com/go/docs/developers to read the Touch Event Injector Sample Application Overview.Development Guide Event injection37
  • Command Framework API 6You can use the Command Framework API in the net.rim.device.api.command package to define functionality that youcan use in different locations in your application or in other applications on the BlackBerry® device.The Command Framework API contains command handlers, command metadata, and commands.Component DescriptionCommand handler You use the CommandHandler class to define functionality that you want to makeavailable in your application or in other applications on the device. You create a class thatextends the abstract CommandHandler class and define the functionality in the classsexecute() method. That functionality is called a command.Command metadata You use the CommandMetadata class to define metadata that describes a command.Each commands metadata is encapsulated in a CommandMetadata object. The onlyrequired piece of metadata for a command is the commands ID, which is provided whenthe CommandMetadata object is constructed and is stored in the objectsCOMMAND_ID field.CommandMetadata provides other fields for you to use to describe the command, suchas RESOURCE_BUNDLE_NAME, to which you can assign the name of the resource bundlethat is used by the command. You can also define metadata items that are specific to aparticular command.Command You use the Command class to execute a command. You can think of a Command instanceas a proxy to an instance of a class that extends CommandHandler. WhenCommand.execute() is invoked, the call is delegated to the associatedCommandHandler instance, passing the current context and transparently passing aread-only version of the associated command metadata for execution.The Command Framework API provides two registries that you can use to store your commands:• You can use the local registry to store commands for use in your application by using theLocalCommandRegistrarConnection class.• You can use the global registry to store commands for use in other applications on the device by using theRemoteCommandRegistrarConnection class.The Command Framework Demo and Command Framework Demo Remote App sample applications are included in theBlackBerry® Java® SDK. These sample applications demonstrate how to define and use commands in a single application andhow to define commands in one application and use them in other applications.Development Guide Command Framework API38
  • Use a command with one UI componentYou can define a command for use with one UI component in your BlackBerry® device application. Using this approach, youdont need to define metadata for the command. The core UI components for BlackBerry device applications that supportcommands include menu items, buttons, pop-up menu items, and toolbars.1. Import the required classes and interfaces.import net.rim.device.api.command.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;2. Create a command handler by creating a class that extends the abstract CommandHandler class. In execute(), definethe functionality that you want to associate with the UI component. To specify whether a command is executable for a givencontext object, you can implement a canExecute() method in your command handler. If you dont implementcanExecute(), your command is always executable.// this command is always executableclass DialogCommandHandler extends CommandHandler{public void execute(ReadOnlyCommandMetadata metadata, Object context){Dialog.alert("Executing command for " + context.toString());}}3. Create the UI component.MenuItem myItem = new MenuItem(new StringProvider("My Menu Item"),0x230000, 0);4. For a menu item or button, you can optionally set the context for the command using the UI componentssetCommandContext() method. For some commands, a context might be needed to determine what the commandshould do. If you dont set a context, the menu item object or button object is the context.myItem.setCommandContext(new Object(){public String toString(){return "My MenuItem Object";}});5. Invoke setCommand() to specify the command for the UI component and provide the command handler as the methodsargument.myItem.setCommand(new Command(new DialogCommandHandler()));6. Add the component to your screen.Development Guide Use a command with one UI component39
  • addMenuItem(myItem);The command is executed when a BlackBerry device user performs an action on the UI component (for example, when the userclicks a menu item).Code samplesFor examples of this approach to defining and using commands, see the API reference for MenuItem and ButtonField.Use a command in one or more applicationsYou can store a command in a local registry for use in your application or store a command in a global registry for use in anyapplication on the BlackBerry® device.1. Import the required classes and interfaces.import net.rim.device.api.command.*;import net.rim.device.api.command.registrar.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;2. Create a command handler by creating a class that extends the abstract CommandHandler class. In execute(), definethe functionality that you want to make available. To specify whether a command is executable for a given context object,you can optionally implement canExecute() in your command handler. If you dont implement canExecute(), yourcommand is always executable.private static class ViewContactCommand extends CommandHandler{public void execute(ReadOnlyCommandMetadata metadata, Object context){// Invoke the Contacts application to view a contact here}public boolean canExecute(ReadOnlyCommandMetadata metadata, Object context){// Return true if the command can be executed// with the passed-in context object.}}3. Define the commands metadata.String id = "com.example.contacts.view.emailaddr";CommandMetadata metadata = new CommandMeta(id);4. If applications that use the command must create instances of the command, store the commands class name in themetadata.Development Guide Use a command in one or more applications40
  • metadata.setClassname(ViewContactCommand.class.getName());Note: Applications can create instances of third-party commands dynamically only if the commands are stored in the localregistry.5. Optionally, define command categories and context categories for the command. Applications that use the command usethe categories to find commands in a registry and to determine whether a command is executable.Category type DescriptionCommand Specifies a type of categorization you want for your command. Applications that use commandscan query a registry for commands in specified categories.Context Specifies the contexts that are appropriate for your command to execute within. You can usethis category to tell applications that use the command what kinds of context objects can bepassed to CommandHandler.Execute().String[] myCommandCategories = {"app.contacts", "action.view"};metadata.setCommandCategories(new CategoryCollection(myCommandCategories));String[] myContextCategories = {emailaddr};metadata.setContextCategories(new CategoryCollection(myContextCategories));6. Register the command.a. If you want your command to be available only in your application, use aLocalCommandRegistrarConnection object. The local registry is available only in the current process.LocalCommandRegistrarConnection connection =new LocalCommandRegistrarConnection();connection.registerCommand(new ViewContactCommand(), metadata);Note: For applications to create instances of the command dynamically, you must register the command only withthe metadata by invoking registerCommand(CommandMetadata)). Otherwise, the registeredCommandHandler is used.b. If you want your command to be available in any application, use a RemoteCommandRegistrarConnectionobject. The global registry is available to all processes that are running on the device.RemoteCommandRegistrarConnection connection =new RemoteCommandRegistrarConnection();connection.registerCommand(new ViewContactCommand(), metadata);7. From another location in your application (for local commands) or from any application on the device (for global commands),retrieve and use the command.a. Create a CommandRequest object and populate it with information about the command that you want to retrievefrom the registry.Development Guide Use a command in one or more applications41
  • CommandRequest request = new CommandRequest();String[] myCommandCategories = {"app.contacts", "action.view"};request.setCommandCategories(new CategoryCollection(myCommandCategories));...b. Retrieve the command from the registry.// using the local registryLocalCommandRegistrarConnection connection =new LocalCommandRegistrarConnection();Command command = connection.getCommand(request);// using the global registryRemoteCommandRegistrarConnection connection =new RemoteCommandRegistrarConnection();Command command = connection.getCommand(request);c. Use the command. The following example executes the command, depending on the context.command.execute(context); // context is the context objectCode samplesTwo sample applications that use the Command Framework API are included in the BlackBerry® Java® SDK:• Command Framework Demo Remote App demonstrates how to create a command and store it in the global registry for usein other applications.• Command Framework Demo demonstrates how to create commands, store them in the local registry, and add them as menuitems in the pop-up menus for the fields, depending on the content of the fields. This sample application also executes acommand that is stored in the global registry by Command Framework Demo Remote App.Development Guide Use a command in one or more applications42
  • Arranging UI components 7You can arrange the UI components on an application screen by using BlackBerry® API layout managers. The following classesextend the Manager class that is provided in the net.rim.device.apu.ui package and provide predefined layouts forthe UI components on your applications screen.Layout manager DescriptionFlowFieldManager This layout manager arranges UI components vertically and then horizontallydepending on the size of the screen. The first UI component is positioned in theupper-leftcornerofthescreenandsubsequentcomponentsareplacedhorizontallyto the right of the first component until the width of the screen is reached. OnceUI components can no longer fit on the first row, the next UI component is placedbelow the first row of components on a row that has a height that is equal to thetallest component of the row above it. You can apply vertical style bits (for example,Field.FIELD_TOP, Field.FIELD_BOTTOM, or Field.FIELD_VCENTER)to align UI components vertically within their row.HorizontalFieldManager This layout manager arranges UI components in a single horizontal row starting atthe left side of the screen and ending at the right side of the screen. Because thislayout manager arranges UI components horizontally, you cannot apply horizontalstyle bits to UI components (for example, Field.FIELD_LEFT,Field.FIELD_HCENTER, or Field.FIELD_RIGHT). You can apply verticalstyle bits (for example, Field.FIELD_TOP, Field.FIELD_BOTTOM, orField.FIELD_VCENTER).If the UI components do not fit the available width of the screen, you should usethe Manager.HORIZONTAL_SCROLL style bit to enable horizontal scrolling.Otherwise, the screen displays as many UI components as possible within theavailable screen width, and the rest are not shown. The UI components exist butare not visible. This situation can create unexpected scrolling behavior for yourusers.VerticalFieldManager This layout manager arranges UI components in a single vertical column startingat the top of the screen and ending at the bottom of the screen. Because this layoutmanager is designed to arrange items vertically, you cannot apply vertical style bitsto UI components (for example, Field.FIELD_TOP,Development Guide Arranging UI components43
  • Layout manager DescriptionField.FIELD_BOTTOM, or Field.FIELD_VCENTER). You can applyhorizontal style bits (for example, Field.FIELD_LEFT,Field.FIELD_HCENTER, or Field.FIELD_RIGHT).You can use additional layout managers to arrange UI components in your application. For example, you can use theGridFieldManager layout manager to position UI components in rows and columns on a screen to create a grid. You canuse the EyelidFieldManager layout manager to display UI components on a pair of managers that appear at the top andbottom of the screen temporarily.Arrange UI components1. Import the required classes and interfaces.net.rim.device.api.ui.container.HorizontalFieldManager;net.rim.device.api.ui.component.ButtonField;2. Create an instance of a HorizontalFieldManager.HorizontalFieldManager _fieldManagerBottom = new HorizontalFieldManager();3. Invoke add() to add the HorizontalFieldManager to a screen.myScreen.add(_fieldManagerBottom);4. Create an instance of a ButtonField.ButtonField mySubmitButton = new ButtonField("Submit");5. Add the ButtonField to the HorizontalFieldManager._fieldManagerBottom.add(mySubmitButton);Creating a grid layoutNote: For information on creating a grid layout in the BlackBerry® Java® Development Environment before version 5.0, visithttp://www.blackberry.com/knowledgecenterpublic to read DB-00783.You can position fields in rows and columns on a screen to create a grid by using the GridFieldManager class. When youcreate a grid, you can specify the number of rows and columns. After you create a grid, you cannot change the number of rowsand columns that it contains.Grids are zero-indexed, so the first cell is located at row 0, column 0. In a locale with a left-to-right text direction, the first cellis in the upper-left corner of the grid.Development Guide Arrange UI components44
  • In a locale with a right-to-left text direction, the first cell is in the upper-right corner of the grid.You can add fields to a grid sequentially (left-to right, top-to-bottom in locales with a left-to-right text direction; right-to-left,top-to-bottom in locales with a right-to-left text direction) or by specifying a row and column in the grid. You can delete fields,insert fields, specify the spacing between columns and rows, and retrieve a grids properties.Grids do not have defined heading rows or heading columns. You can emulate the appearance of headings by changing theappearance of the fields in the grids first row or first column.Grids can scroll horizontally or vertically if the grids width or height exceeds the screens visible area.You can specify column width by invoking GridFieldManager.setColumnProperty(), and you can specify row heightby invoking GridFieldManager.setRowProperty(). When you invoke these methods, you must specify aGridFieldManager property.Property DescriptionFIXED_SIZE width or height is a fixed size in pixelsPREFERRED_SIZE width or height is a preferred size based on the maximum preferred sizeof the fields in the column or row (PREFERRED_SIZE is the defaultproperty)PREFERRED_SIZE_WITH_MAXIMUM width or height is a preferred size up to a maximum sizeAUTO_SIZE width or height is based on available screen spaceDevelopment Guide Creating a grid layout45
  • Create a grid layout1. Import the required classes and interfaces.import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor,invoke pushScreen() to display the custom screen for the application. In the sample, the GridScreen class, describedin step 3, represents the custom screen.class GridFieldManagerDemo extends UiApplication{public static void main(String[] args){GridFieldManagerDemo theApp = new GridFieldManagerDemo();theApp.enterEventDispatcher();}GridFieldManagerDemo(){pushScreen(new GridScreen());}}3. Create the framework for the custom screen by extending the MainScreen class.class GridScreen extends MainScreen{public GridScreen(){}}4. In the screen constructor, invoke setTitle() to set the text that you want to appear in the title section of the screen.setTitle("GridFieldManager Demo");5. In the screen constructor, create an instance of the GridFieldManager class. Specify the number of rows, the numberof columns, and the style of the grid (using a style inherited from net.rim.device.api.ui.Manager). Specify 0 forthe style to use the default style.GridFieldManager grid;grid = new GridFieldManager(2,3,0);6. In the screen constructor, invoke GridFieldManager.add() to add fields to the grid.Development Guide Creating a grid layout46
  • grid.add(new LabelField("one"));grid.add(new LabelField("two"));grid.add(new LabelField("three"));grid.add(new LabelField("four"));grid.add(new LabelField("five"));7. In the screen constructor, invoke the GridFieldManagerset() methods to specify the properties of the grid.grid.setColumnPadding(20);grid.setRowPadding(20);8. In the screen constructor, invoke Screen.add() to add the grid to the screen.add(grid);After you finish:You can change the grid after you create it. For example, you can add fields, delete fields, or change the grids properties.Code sample: Creating a grid layout/** GridFieldManagerDemo.java** Research In Motion Limited proprietary and confidential* Copyright Research In Motion Limited, 2009*/import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;public class GridFieldManagerDemo extends UiApplication{public static void main(String[] args){GridFieldManagerDemo theApp = new GridFieldManagerDemo();theApp.enterEventDispatcher();}GridFieldManagerDemo(){pushScreen(new GridScreen());}}class GridScreen extends MainScreen{public GridScreen(){setTitle("GridFieldManager Demo");Development Guide Creating a grid layout47
  • GridFieldManager grid = new GridFieldManager(2,3,0);grid.add(new LabelField("one"));grid.add(new LabelField("two"));grid.add(new LabelField("three"));grid.add(new LabelField("four"));grid.add(new LabelField("five"));grid.setColumnPadding(20);grid.setRowPadding(20);add(grid);// The grid looks like this:// | one | two | three// | four | five |// insert a cell first row, second columngrid.insert(new LabelField("insert"), 0, 1);// The grid now looks like this:// | one | insert | two// | three | four | five// delete a cell second row, second columngrid.delete(1,1);// The grid now looks like this:// | one | insert | two// | three | | five// Add field to first unoccupied cellgrid.add(new LabelField("new"));// The grid now looks like this:// | one | insert | two// | three | new | five}}Displaying fields on a temporary pair of managersYou can use the EyelidFieldManager class to display fields on a pair of managers that appear on the top and bottom ofthe screen temporarily.Development Guide Displaying fields on a temporary pair of managers48
  • By default, the fields appear when the BlackBerry® device user moves the trackball or, for a device with a touch screen, when atouch event occurs. The fields disappear after a period of inactivity (1.2 seconds by default). You can override these defaultproperties.There is no limit to the number and size of the fields. If the managers contain more fields than can fit on the screen, the top andbottom managers overlap with the top manager in the foreground.Display a ButtonField and a LabelField temporarily on the top and bottom of the screen1. Import the required classes and interfaces.import net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;import net.rim.device.api.ui.extension.container.*;2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor,invoke pushScreen() to display the custom screen for the application. The EyelidFieldManagerDemoScreenclass, described in step 3, represents the custom screen.public class EyelidFieldManagerDemo extends UiApplication{public static void main(String[] args){EyelidFieldManagerDemo app = new EyelidFieldManagerDemo();app.enterEventDispatcher();}public EyelidFieldManagerDemo(){pushScreen(new EyelidFieldManagerDemoScreen());}}3. Create the framework for the custom screen by extending the MainScreen class.class EyelidFieldManagerDemoScreen extends MainScreen {{public EyelidFieldManagerDemoScreen(){}}4. In the screen constructor, invoke setTitle() to specify the text that appears in the title section of the screen.setTitle("EyelidFieldManager Demo");5. In the screen constructor, create an instance of the EyelidFieldManager class.Development Guide Displaying fields on a temporary pair of managers49
  • EyelidFieldManager manager = new EyelidFieldManager();6. In the screen constructor, invoke EyelidFieldManager.addTop() to add a LabelField object to the top managerof the EyelidFieldManager.manager.addTop(new LabelField("Hello World"));7. In the screen constructor, create a HorizontalFieldManager object. Invoke HorizontalFieldManager.add() to add buttons to the HorizontalFieldManager. Invoke EyelidFieldManager.addBottom() to add theHorizontalFieldManager to the bottom manager of the EyelidFieldManager.HorizontalFieldManager buttonPanel = new HorizontalFieldManager(Field.FIELD_HCENTER | Field.USE_ALL_WIDTH);buttonPanel.add(new SimpleButton("Button 1"));buttonPanel.add(new SimpleButton("Button 2"));manager.addBottom(buttonPanel);8. In the screen constructor, invoke EyelidFieldManager.setEyelidDisplayTime() to specify, in milliseconds,the period of inactivity that must elapse before the pair of managers disappear.manager.setEyelidDisplayTime(3000);9. In the screen constructor, invoke add() to add the EyelidFieldManager to the screen.add(manager);Code sample: Displaying a ButtonField and a LabelField temporarily on the top and bottom of the screenimport net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;import net.rim.device.api.ui.extension.container.*;public class EyelidFieldManagerDemo extends UiApplication{public static void main(String[] args){EyelidFieldManagerDemo app = new EyelidFieldManagerDemo();app.enterEventDispatcher();}public EyelidFieldManagerDemo(){pushScreen(new EyelidFieldManagerDemoScreen());}}class EyelidFieldManagerDemoScreen extends MainScreen{Development Guide Displaying fields on a temporary pair of managers50
  • public EyelidFieldManagerDemoScreen(){setTitle("EyelidFieldManager Demo");EyelidFieldManager manager = new EyelidFieldManager();manager.addTop(new LabelField("Hello World"));HorizontalFieldManager buttonPanel = new HorizontalFieldManager(Field.FIELD_HCENTER | Field.USE_ALL_WIDTH);buttonPanel.add(new ButtonField("Button 1"));buttonPanel.add(new ButtonField("Button 2"));manager.addBottom(buttonPanel);manager.setEyelidDisplayTime(3000);add(manager);}}Displaying a field at an absolute position on a screenYou can use the AbsoluteFieldManager class to specify an absolute position, based on x-y co-ordinates, of a field on ascreen rather than a position that is relative to other fields on the screen.You can use the AbsoluteFieldManager class to control of the placement of fields and to overlap fields on the screen.Display a label at an absolute position on the screen1. Import the required classes and interfaces.import net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;import net.rim.device.api.ui.component.*;2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor,invoke pushScreen() to display the custom screen for the application. TheAbsoluteFieldManagerDemoScreen class, described in step 3, represents the custom screen.public class AbsoluteFieldManagerDemo extends UiApplication{public static void main(String[] args){AbsoluteFieldManagerDemo app = new AbsoluteFieldManagerDemo();Development Guide Displaying a field at an absolute position on a screen51
  • app.enterEventDispatcher();}public AbsoluteFieldManagerDemo(){pushScreen(new AbsoluteFieldManagerDemoScreen());}}3. Create the framework for the custom screen by extending the MainScreen class. Invoke setTitle() to specify thetext that appears in the title section of the screen.class AbsoluteFieldManagerDemoScreen extends MainScreen{public AbsoluteFieldManagerDemoScreen(){setTitle("AbsoluteFieldManager Demo");}}4. In the screen constructor, create an instance of the AbsoluteFieldManager class.AbsoluteFieldManager manager = new AbsoluteFieldManager();5. In the screen constructor, create and initialize a variable to store the y co-ordinate that corresponds to the vertical centerof the screen.int halfwayDown = Display.getHeight() / 2;6. In the screen constructor, invoke AbsoluteFieldManager.add() to add a LabelField object at the vertical centerof the screen and with an x co-ordinate of 2.manager.add(new LabelField("Hello world"), 2, halfwayDown);7. In the screen constructor, invoke add() to add the AbsoluteFieldManager to the screen.add(manager);Code sample: Displaying a label at an absolute position on the screenimport net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;import net.rim.device.api.ui.component.*;public class AbsoluteFieldManagerDemo extends UiApplication{public static void main(String[] args){AbsoluteFieldManagerDemo app = new AbsoluteFieldManagerDemo();app.enterEventDispatcher();}Development Guide Displaying a field at an absolute position on a screen52
  • public AbsoluteFieldManagerDemo(){pushScreen(new AbsoluteFieldManagerDemoScreen());}}class AbsoluteFieldManagerDemoScreen extends MainScreen{public AbsoluteFieldManagerDemoScreen(){setTitle("AbsoluteFieldManager Demo");AbsoluteFieldManager manager = new AbsoluteFieldManager();int halfwayDown = Display.getHeight() / 2;manager.add(new LabelField("Hello world"), 2, halfwayDown);add(manager);}}Development Guide Displaying a field at an absolute position on a screen53
  • UI components 8Add a UI component to a screen1. Import the following classes:• net.rim.device.api.ui.component.CheckboxField• net.rim.device.api.ui.container.MainScreen2. Create an instance of a UI component.CheckboxField myCheckbox = new CheckboxField("First checkbox", true);3. Add the UI component to your extension of a Screen class.mainScreen.add(myCheckbox);Aligning a field to a line of textYou can create an application that can align a Field object to the natural beginning of a line of text by using the flagField.FIELD_LEADING. For example, if you create a Field with the alignment flag Field.FIELD_LEADING, and addthe Field to a VerticalFieldManager, if the application starts using either English or Chinese locales for example, theField aligns to the left side of the screen. If the application starts using either Arabic or Hebrew locales, the Field aligns tothe right side of the screen.ButtonsUsebuttonstoallowuserstoperformanactionfromadialogbox.Menustypicallyincludeactionsthatareassociatedwithascreen.Users can perform the following actions with a button:Action BlackBerry devices with a trackpad onlyBlackBerry devices with a touch screenand a trackpadHighlight a button. Move a finger on the trackpad. • Touch the button lightly.• Move a finger on the trackpad.Perform an action. Click the trackpad or press the Enter key. • Tap the item.• Click the trackpad.• Press the Enter key.Development Guide UI components54
  • Best practice: Implementing buttons• Avoid using buttons on an application screen. To provide actions that are associated with a screen, use the application menuinstead. On BlackBerry® devices with a trackpad, the menu is available to users immediately, regardless of the position ofthe cursor on the screen. Buttons are static and require users to highlight a button to perform the associated action. If youuse buttons, include menu items for the actions in the application menu as well. On BlackBerry devices with a touch screen,you can use buttons for critical actions.• Use check boxes for options such as turning on or turning off a feature.• Use the ButtonField class to create buttons.• For the default button, use the button that users are most likely to click. Avoid using a button that is associated with adestructive action as the default button.Guidelines for labels• Use clear, concise labels.• Use one-word labels where possible. The size of a button changes depending on the length of the label. If a label is toolong, an ellipsis (...) indicates that the text is truncated.• Use verbs for labels that describe the associated action (for example, "Cancel," "Delete," "Discard," or "Save"). If necessary,include more descriptive text elsewhere on the screen (for example, in an application message).• Avoid using the labels "Yes" and "No."• Avoid using punctuation in a label. Use an ellipsis in a button label to indicate that users must perform another action afterthey click the button.Create a button1. Import the net.rim.device.api.ui.component.ButtonField class.2. Create an instance of a ButtonField using a style parameter.ButtonField mySubmitButton = new ButtonField("Submit");Development Guide Buttons55
  • Check boxesUse check boxes for binary options that users can understand easily. For example, use a check box for an option that can beturned on and off.Users can perform the following action with a check box:Action BlackBerry devices with a trackpad onlyBlackBerry devices with a touch screenand a trackpadSelect a check box. Press the Space key or click the trackpad. • Tap the item.• Press the Space key.• Click the trackpad.Best practice: Implementing check boxes• Use check boxes when users can select multiple options.• Use the CheckboxField class to create check boxes.• Do not start an action when users select a check box. For example, do not open a new screen.• Align check boxes vertically.• Group and order check boxes logically (for example, group related options together or include the most common optionsfirst). Avoid ordering check boxes alphabetically; alphabetical order is language specific.Guidelines for labels• Use clear, concise labels. Verify that the label clearly describes what occurs when users select the check box.Development Guide Check boxes56
  • • Use positive labels where possible. For example, if users have the option of turning on or turning off a feature, use "turn on"instead of "turn off" in the label.• Place labels on the right side of check boxes. On Option screens, place labels on the left side of check boxes.• Use sentence case capitalization.• Punctuate labels for check boxes with a colon (:).Create a check box1. Import the required classes and interfaces.import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor,invoke pushScreen() to display the custom screen for the application. The MyUiScreen class, which is described instep 3, represents the custom screen.public class MyUi extends UiApplication{public static void main(String[] args){MyUi theApp = new MyUi();theApp.enterEventDispatcher();}public MyUi(){pushScreen(new MyUiScreen());}}3. Create the custom screen for the application by extending the MainScreen class. In the screen constructor, invokesetTitle() to specify the title for the screen.class MyUiScreen extends MainScreen{public MyUiScreen(){setTitle("UI Component Sample");}}4. In the screen constructor, create a check box by using the CheckboxField class. In the CheckboxField constructor,specify the label for the check box and use a Boolean value to indicate whether the check box is the default selection (forexample,true indicates that by default the check box is selected). Invoke add() to add the check box to the screen.add(new CheckboxField("First Check Box", true));add(new CheckboxField("Second Check Box", false));Development Guide Check boxes57
  • 5. To change the default behavior of a check box, use the styles that are inherited from the Field class. For example, to createa check box that users cannot change, use the READONLY style.add(new CheckboxField("First Check Box", true, this.READONLY));6. To override the default functionality that prompts the user to save changes before the application closes, in the extensionof the MainScreen class, override the MainScreen.onSavePrompt() method. In the following code sample, thereturn value is true which indicates that the application does not prompt the user before closing.public boolean onSavePrompt(){return true;}Code sample: Creating a check boximport net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;public class MyUi extends UiApplication{public static void main(String[] args){MyUi theApp = new MyUi();theApp.enterEventDispatcher();}public MyUi(){pushScreen(new MyUiScreen());}}class MyUiScreen extends MainScreen{public MyUiScreen(){setTitle("UI Component Sample");add(new CheckboxField("First Check Box", true));add(new CheckboxField("Second Check Box", false));}public boolean onSavePrompt(){return true;}}Development Guide58
  • Create a bitmap1. Import the net.rim.device.api.ui.component.BitmapField class.2. Create an instance of a BitmapField.BitmapField myBitmapField = new BitmapField();Create a custom fieldYou can only add custom context menu items and custom layouts to a custom field.1. Import the following classes:• net.rim.device.api.ui.Field• java.lang.String• net.rim.device.api.ui.Font• java.lang.Math• net.rim.device.api.ui.Graphics2. Import the net.rim.device.api.ui.DrawStyle interface.3. Extend the Field class, or one of its subclasses, implementing the DrawStyle interface to specify the characteristics ofthe custom field and turn on drawing styles.public class CustomButtonField extends Field implements DrawStyle {public static final int RECTANGLE = 1;public static final int TRIANGLE = 2;public static final int OCTAGON = 3;private String _label;private int _shape;private Font _font;private int _labelHeight;private int _labelWidth;}4. Implement constructors to define a label, shape, and style of the custom button.public CustomButtonField(String label) {this(label, RECTANGLE, 0);}public CustomButtonField(String label, int shape) {this(label, shape, 0);}public CustomButtonField(String label, long style) {this(label, RECTANGLE, style);}public CustomButtonField(String label, int shape, long style) {super(style);Development Guide Create a bitmap59
  • _label = label;_shape = shape;_font = getFont();_labelHeight = _font.getHeight();_labelWidth = _font.getAdvance(_label);}5. Implement layout() to specify the arrangement of field data. Perform the most complex calculations in layout()instead of in paint(). The manager of the field invokes layout() to determine how the field arranges its contents in theavailable space. Invoke Math.min() to return the smaller of the specified width and height, and the preferred width andheight of the field. Invoke Field.setExtent(int,int) to set the required dimensions for the field.protected void layout(int width, int height) {_font = getFont();_labelHeight = _font.getHeight();_labelWidth = _font.getAdvance(_label);width = Math.min( width, getPreferredWidth() );height = Math.min( height, getPreferredHeight() );setExtent( width, height );}6. Implement getPreferredWidth(), using the relative dimensions of the field label to make sure that the label does notexceed the dimensions of the component. Use a switch block to determine the preferred width based on the shape of thecustom field. For each type of shape, use an if statement to compare dimensions and determine the preferred width for thecustom field.public int getPreferredWidth() {switch(_shape) {case TRIANGLE:if (_labelWidth < _labelHeight) {return _labelHeight << 2;} else {return _labelWidth << 1;}case OCTAGON:if (_labelWidth < _labelHeight) {return _labelHeight + 4;} else {return _labelWidth + 8;}case RECTANGLE: default:return _labelWidth + 8;}}7. Implement getPreferredHeight(), using the relative dimensions of the field label to determine the preferred height.Use a switch block to determine the preferred height based on the shape of the custom field. For each type of shape, usean if statement to compare dimensions and determine the preferred height for the custom field.Development Guide Create a custom field60
  • public int getPreferredHeight() {switch(_shape) {case TRIANGLE:if (_labelWidth < _labelHeight) {return _labelHeight << 1;} else {return _labelWidth;}case RECTANGLE:return _labelHeight + 4;case OCTAGON:return getPreferredWidth();}return 0;}8. Implement paint(). The manager of a field invokes paint() to redraw the field when an area of the field is marked asinvalid. Use a switch block to repaint a custom field based on the shape of the custom field. For a field that has a triangleor octagon shape, use the width of the field to calculate the horizontal and vertical position of a lines start point and endpoint. Invoke graphics.drawLine() and use the start and end points to draw the lines that define the custom field.For a field that has a rectangular shape, invoke graphics.drawRect() and use the width and height of the field todraw the custom field. Invoke graphics.drawText() and use the width of the field to draw a string of text to an areaof the fieldprotected void paint(Graphics graphics) {int textX, textY, textWidth;int w = getWidth();switch(_shape) {case TRIANGLE:int h = (w>>1);int m = (w>>1)-1;graphics.drawLine(0, h-1, m, 0);graphics.drawLine(m, 0, w-1, h-1);graphics.drawLine(0, h-1, w-1, h-1);textWidth = Math.min(_labelWidth,h);textX = (w - textWidth) >> 1;textY = h >> 1;break;case OCTAGON:int x = 5*w/17;int x2 = w-x-1;int x3 = w-1;graphics.drawLine(0, x, 0, x2);graphics.drawLine(x3, x, x3, x2);graphics.drawLine(x, 0, x2, 0);graphics.drawLine(x, x3, x2, x3);graphics.drawLine(0, x, x, 0);graphics.drawLine(0, x2, x, x3);graphics.drawLine(x2, 0, x3, x);graphics.drawLine(x2, x3, x3, x2);Development Guide Create a custom field61
  • textWidth = Math.min(_labelWidth, w - 6);textX = (w-textWidth) >> 1;textY = (w-_labelHeight) >> 1;break;case RECTANGLE: default:graphics.drawRect(0, 0, w, getHeight());textX = 4;textY = 2;textWidth = w - 6;break;}graphics.drawText(_label, textX, textY, (int)( getStyle() & DrawStyle.ELLIPSIS| DrawStyle.HALIGN_MASK ), textWidth );}9. Implement the Fieldset() and get() methods. Implement the Field.getLabel(), Field.getShape(),Field.setLabel(Stringlabel), and Field.setShape(intshape) methods to return the instance variablesof the custom field.public String getLabel() {return _label;}public int getShape() {return _shape;}public void setLabel(String label) {_label = label;_labelWidth = _font.getAdvance(_label);updateLayout();}public void setShape(int shape) {_shape = shape;}Creating a field to display web contentDisplay HTML content in a browser field1. Import the required classes and interfaces.import net.rim.device.api.browser.field2.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor,invoke pushScreen() to display the custom screen for the application. The BrowserFieldDemoScreen class,described in step 3, represents the custom screen.Development Guide Creating a field to display web content62
  • public class BrowserFieldDemo extends UiApplication{public static void main(String[] args){BrowserFieldDemo app = new BrowserFieldDemo();app.enterEventDispatcher();}public BrowserFieldDemo(){pushScreen(new BrowserFieldDemoScreen());}}3. Create the custom screen by extending the MainScreen class.class BrowserFieldDemoScreen extends MainScreen{public BrowserFieldDemoScreen(){}}4. In the screen constructor, create an instance of the BrowserField class.BrowserField myBrowserField = new BrowserField();5. In the screen constructor, invoke add() to add the BrowserField object to the screen.add(myBrowserField);6. In the screen constructor, invoke BrowserField.displayContent() to specify and display the HTML content.myBrowserField.displayContent("<html><body><h1>Hello World!</h1></body></html>", "http://localhost");Code sample: Displaying HTML content in a browser fieldimport net.rim.device.api.browser.field2.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;public class BrowserFieldDemo extends UiApplication{public static void main(String[] args){BrowserFieldDemo app = new BrowserFieldDemo();app.enterEventDispatcher();}public BrowserFieldDemo(){pushScreen(new BrowserFieldDemoScreen());Development Guide Creating a field to display web content63
  • }}class BrowserFieldDemoScreen extends MainScreen{public BrowserFieldDemoScreen(){BrowserField myBrowserField = new BrowserField();add(myBrowserField);myBrowserField.displayContent("<html><body><h1>HelloWorld!</h1></body></html>", "http://localhost");}}Display HTML content from a web page in a browser field1. Import the required classes and interfaces.import net.rim.device.api.browser.field2.*;import net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor,invoke pushScreen() to display the custom screen for the application. The BrowserFieldDemoScreen class,described in step 3, represents the custom screen.public class BrowserFieldDemo extends UiApplication{public static void main(String[] args){BrowserFieldDemo app = new BrowserFieldDemo();app.enterEventDispatcher();}public BrowserFieldDemo(){pushScreen(new BrowserFieldDemoScreen());}}3. Create the framework for the custom screen by extending the MainScreen class.class BrowserFieldDemoScreen extends MainScreen{public BrowserFieldDemoScreen(){}}Development Guide Creating a field to display web content64
  • 4. In the screen constructor, create an instance of the BrowserField class.BrowserField myBrowserField = new BrowserField();5. In the screen constructor, invoke add() to add the BrowserField object to the screen.add(myBrowserField);6. In the screen constructor, invoke BrowserField.requestContent() to specify the location of the HTML contentand display it.myBrowserField.requestContent("http://www.blackberry.com");Code sample: Displaying HTML content from a web page in a browser fieldimport net.rim.device.api.browser.field2.*;import net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;public class BrowserFieldDemo extends UiApplication{public static void main(String[] args){BrowserFieldDemo app = new BrowserFieldDemo();app.enterEventDispatcher();}public BrowserFieldDemo(){pushScreen(new BrowserFieldDemoScreen());}}class BrowserFieldDemoScreen extends MainScreen{public BrowserFieldDemoScreen(){BrowserField myBrowserField = new BrowserField();add(myBrowserField);myBrowserField.requestContent("http://www.blackberry.com");}}Display HTML content from a resource in your application1. Import the required classes and interfaces.Development Guide Creating a field to display web content65
  • import net.rim.device.api.browser.field2.*;import net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor,invoke pushScreen() to display the custom screen for the application. The BrowserFieldDemoScreen class,described in step 3, represents the custom screen.public class BrowserFieldDemo extends UiApplication{public static void main(String[] args){BrowserFieldDemo app = new BrowserFieldDemo();app.enterEventDispatcher();}public BrowserFieldDemo(){pushScreen(new BrowserFieldDemoScreen());}}3. Create the custom screen by extending the MainScreen class.class BrowserFieldDemoScreen extends MainScreen{public BrowserFieldDemoScreen(){}}4. In the screen constructor, create an instance of the BrowserField class.BrowserField myBrowserField = new BrowserField();5. In the screen constructor, invoke add() to add the BrowserField object to the screen.add(myBrowserField);6. In the screen constructor, invoke BrowserField.requestContent() to specify the location of the resource in yourapplication and display the HTML content.myBrowserField.requestContent("local:///test.html");Note: The BrowserField class does not access resources using a folder structure. The BrowserField class displays thefirst resource found that matches the specifed file name.Development Guide Creating a field to display web content66
  • Code sample: Displaying HTML content from a resource in your applicationimport net.rim.device.api.browser.field2.*;import net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;public class BrowserFieldDemo extends UiApplication{public static void main(String[] args){BrowserFieldDemo app = new BrowserFieldDemo();app.enterEventDispatcher();}public BrowserFieldDemo(){pushScreen(new BrowserFieldDemoScreen());}}class BrowserFieldDemoScreen extends MainScreen{public BrowserFieldDemoScreen(){BrowserField myBrowserField = new BrowserField();add(myBrowserField);myBrowserField.requestContent("local:///test.html");}}Configure a browser field1. Import the required classes and interfaces.import net.rim.device.api.browser.field2.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor,invoke pushScreen() to display the custom screen for the application. The BrowserFieldDemoScreen class,described in step 3, represents the custom screen.public class BrowserFieldDemo extends UiApplication{public static void main(String[] args){BrowserFieldDemo app = new BrowserFieldDemo();Development Guide Creating a field to display web content67
  • app.enterEventDispatcher();}public BrowserFieldDemo(){pushScreen(new BrowserFieldDemoScreen());}}3. Create the framework for the custom screen by extending the MainScreen class.class BrowserFieldDemoScreen extends MainScreen{public BrowserFieldDemoScreen(){}}4. In the screen constructor, create an instance of the BrowserFieldConfig class.BrowserFieldConfig myBrowserFieldConfig = new BrowserFieldConfig();5. In the screen constructor, invoke BrowserFieldConfig.setProperty() to specify a property of theBrowserField. The first parameter in setProperty() specifies the property, and the second parameter specifies thevalue of the property. For example, the following code sample specifies the NAVIGATION_MODE property of aBrowserField object:myBrowserFieldConfig.setProperty(BrowserFieldConfig.NAVIGATION_MODE,BrowserFieldConfig.NAVIGATION_MODE_POINTER);6. In the screen constructor, create an instance of the BrowserField class that uses the configuration that you defined.BrowserField browserField = new BrowserField(myBrowserFieldConfig);Code sample: Configuring a browser fieldimport net.rim.device.api.browser.field2.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;public class BrowserFieldDemo extends UiApplication{public static void main(String[] args){BrowserFieldDemo app = new BrowserFieldDemo();app.enterEventDispatcher();}public BrowserFieldDemo(){pushScreen(new BrowserFieldDemoScreen());}}Development Guide Creating a field to display web content68
  • class BrowserFieldDemoScreen extends MainScreen{public BrowserFieldDemoScreen(){BrowserFieldConfig myBrowserFieldConfig = new BrowserFieldConfig();myBrowserFieldConfig.setProperty(BrowserFieldConfig.NAVIGATION_MODE,BrowserFieldConfig.NAVIGATION_MODE_POINTER);BrowserField browserField = new BrowserField(myBrowserFieldConfig);}}Send form data to a web address in a browser field1. Import the required classes and interfaces.import net.rim.device.api.browser.field2.*;import net.rim.device.api.io.http.*;import net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;import java.lang.*;import java.util.*;2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor,invoke pushScreen() to display the custom screen for the application. The BrowserFieldDemoScreen class,described in step 3, represents the custom screen.public class BrowserFieldDemo extends UiApplication{public static void main(String[] args){BrowserFieldDemo app = new BrowserFieldDemo();app.enterEventDispatcher();}public BrowserFieldDemo(){pushScreen(new BrowserFieldDemoScreen());}}3. Create the custom screen by extending the MainScreen class.class BrowserFieldDemoScreen extends MainScreen{public BrowserFieldDemoScreen()Development Guide Creating a field to display web content69
  • {}}4. In the screen constructor, create an instance of the BrowserField class.BrowserField browserField = new BrowserField();5. In the screen constructor, invoke add() to add the BrowserField object to the screen.add(browserField);6. In the screen constructor, create a String object that contains the base web address of the web page that you are sendingthe form data to.String baseURL = "http://www.blackberry.com";7. In the screen constructor, create a String that specifies the form data that your application sends to the web page.String postData = "fieldname1=value1&fieldname2=value2";8. In the screen constructor, create a Hashtable object to store the header information for the form data.Hashtable header = new Hashtable();9. In the screen constructor, invoke Hashtable.put() to specify the header information for the form data.header.put("Content-Length", "" + postData.length());header.put("Content-Type", "application/x-www-form-urlencoded");10. In the screen constructor, invoke BrowserField.requestContent() to send the form data to the web page anddisplay the web page.browserField.requestContent(baseURL, postData.getBytes(), newHttpHeaders(header));Code sample: Sending form data to a web address in a browser fieldimport net.rim.device.api.browser.field2.*;import net.rim.device.api.io.http.*;import net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;import java.lang.*;import java.util.*;public class BrowserFieldDemo extends UiApplication{public static void main(String[] args){BrowserFieldDemo app = new BrowserFieldDemo();app.enterEventDispatcher();}Development Guide Creating a field to display web content70
  • public BrowserFieldDemo(){pushScreen(new BrowserFieldDemoScreen());}}class BrowserFieldDemoScreen extends MainScreen{public BrowserFieldDemoScreen(){BrowserField browserField = new BrowserField();}add(browserField);String baseURL = "http://www.blackberry.com";String postData = "fieldname1=value1&fieldname2=value2";Hashtable header = new Hashtable();header.put("Content-Length", "" + postData.length());header.put("Content-Type", "application/x-www-form-urlencoded");browserField.requestContent(baseURL, postData.getBytes(), newHttpHeaders(header));}}Dialog boxesUse dialog boxes to perform the following actions:• Prompt users for information that is required to complete a user-initiated task.• Inform users of urgent information or the status of important actions.• Warn users of unexpected or potentially destructive conditions or situations.Dialog boxes are modal; they interrupt the normal operation of the BlackBerry® device and are pushed to the top of the stack.A dialog box includes a message, buttons that allow users to perform an action, and an indicator that indicates the type of dialogbox.ThesizeofthedialogboxdependsonthesizeoftheBlackBerrydevicescreen.ThethemethatusersselectontheirBlackBerrydevice determines the visual style of the dialog box.Development Guide Dialog boxes71
  • Best practice: Implementing dialog boxes• Use buttons to confirm or cancel actions in dialog boxes. Avoid using links or other components.• Use a standard indicator that is appropriate for the type of dialog box. Avoid using multiple indicators in a dialog box.• Try to avoid making users scroll in a dialog box. Include scroll arrows if your dialog box message or buttons cannot bedisplayed fully on the dialog box. If you use standard components, scroll arrows appear automatically if necessary.• Always allow users to use the Escape key to close a dialog box. Avoid implementing another action when users press theEscape key to close a dialog box. For example, if a dialog box allows users to change a setting, do not implement any changeswhen users press the Escape key. If necessary, display the dialog box at a later time.• IfuserspresstheEnd/Powerkeywhenadialogboxappearsonanapplicationscreen,displaytheHomescreenorapplicationlist. If users return to the application, display the dialog box again.Guidelines for layout• Center the dialog box on the screen. If you use standard components, the BlackBerry® device automatically centers thedialog box.• Create dialog boxes that are up to, but not greater than, 90% of the width and height of the screen. If you use standardcomponents, the BlackBerry device automatically calculates the appropriate size for dialog boxes.• Center the dialog box indicator vertically with the dialog box message.• Display messages to the right of the indicator and above any buttons for most languages.• Place buttons for confirmation actions first. For example, place "Save" before "Discard" or "Cancel."• Center buttons horizontally in dialog boxes.• Place buttons vertically in the dialog box. The vertical layout allows buttons to expand to accommodate localized buttonlabels.• If you include a check box, match the alignment of the check box with the alignment of the dialog box message. Place thecheck box above the buttons. The check box should be checked by default, unless the dialog box displays a message withcritical information for users.Development Guide Dialog boxes72
  • Guidelines for messages• Be specific. If possible, use one short sentence to clearly state the reason for displaying the dialog box and the actions thatcan dismiss it.• Use complete sentences for messages where possible.• Use vocabulary that users understand. For example, use "The file could not be saved because the media card is full" insteadof "Error writing file to disk."• Use positive language where possible and avoid blaming the user. Never write messages that blame users for errors orunexpected conditions. Instead, focus on the actions that users can take to resolve the issue.• Use the second person (you, your) to refer to users.• Use sentence case capitalization.• Avoid using exclamation points (!) in messages.• Avoid using an ellipsis (...) in messages unless you are indicating progress (for example, "Please wait...").Guidelines for buttons• For the default button, use the button that users are most likely to click. Avoid using a button that is associated with adestructive action as the default button. Exceptions to this rule are those cases where users initiate a minor destructiveaction (such as deleting a single item) and the most common user action is to continue with the action.• Avoid using more than three buttons in a dialog box. If there are more than three, consider using an application screeninstead with radio buttons.• On BlackBerry devices with a physical keyboard, provide shortcut keys for buttons. Typically, the shortcut key is the firstletter of the button label.• Use clear, concise labels.• Use one-word labels where possible. The size of a button changes depending on the length of the label. If a label is toolong, an ellipsis (...) indicates that the text is truncated.• Avoid using the labels "Yes" and "No." Use verbs that describe the associated action (for example, "Cancel," "Delete,""Discard," or "Save"). This approach helps users quickly and easily understand what happens when they click the button.If necessary, include more descriptive text elsewhere on the screen (for example, in an application message).• Avoid using symbols or graphics in labels.Development Guide Dialog boxes73
  • • Avoid using punctuation in labels. Use an ellipsis in a button label to indicate that additional information is required beforethe associated action can be performed.Create a dialog boxUse alert dialog boxes to notify users of a critical action such as turning off the BlackBerry® device or an error such as typinginformation that is not valid. An exclamation point (!) indicator appears in an alert dialog box. To close an alert dialog box, userscan click OK or press the Escape key. For more information on other types of dialog boxes, see the API reference for BlackBerry®Java® Development Environment.1. Import the net.rim.device.api.ui.component.Dialog class.2. Create an alert dialog box specifying the alert text that you want to display.Dialog.alert("Specify the alert text that you want to display.")Drop-down listsUse drop-down lists to provide a set of mutually exclusive values.Users can perform the following action with a drop-down list:Action BlackBerry devices with a trackpad onlyBlackBerry devices with a touch screenand a trackpadClick a value from a drop-downlist.Press the Enter key or click the trackpad. • Tap the item.• Press the Enter key.• Click the trackpad.Development Guide Drop-down lists74
  • Best practice: Implementing drop-down lists• Use a drop-down list for two or more choices when space is an issue. If space is not an issue, consider using radio buttonsinstead so that users can view the available options on the screen.• Use the ObjectChoiceField or NumericChoiceField class to create drop-down lists.• For the default value, use the value that users are most likely to click.• Use the highlighted option as the default focus when users scroll through the list.• If users are not required to click a value, include a "None" value in the drop-down list. Always place the "None" value atthe top of the list.• Group and order values logically (for example, group related values together or include the most common values first). Avoidordering values alphabetically; alphabetical order is language specific.Guidelines for labels• Use clear, concise labels for drop-down lists and for the values in drop-down lists. Verify that the label clearly describeswhat occurs when users click the value. The width of the drop-down list changes based on the length of the value labels.If a label is too long, an ellipsis (...) appears to indicate that the text is truncated.• Avoid using the labels "Yes" and "No" as drop-down list values. Rephrase the option and use a check box instead.• Place the label on the left side of a drop-down list.• Use title case capitalization for drop-down list labels and values (unless the values read more like a sentence).• Punctuate labels for drop-down lists with a colon (:).Create a drop-down list1. Import the required classes and interfaces.import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor,invoke pushScreen() to display the custom screen for the application. The MyUiScreen class, which is described instep 3, represents the custom screen.public class MyUi extends UiApplication{public static void main(String[] args){MyUi theApp = new MyUi();theApp.enterEventDispatcher();}public MyUi(){Development Guide Drop-down lists75
  • pushScreen(new MyUiScreen());}}3. Create the custom screen for the application by extending the MainScreen class. In the screen constructor, invokesetTitle() to specify the title for the screen.class MyUiScreen extends MainScreen{public MyUiScreen(){setTitle("UI Component Sample");}}4. In the screen constructor, create a drop-down list that displays a list of words or phrases by using theObjectChoiceField class. Create a String array to store the items that you want to display in the drop-down list.Create an int to store the default item to display in the drop-down list. In the ObjectChoiceField constructor, specifythe label for the drop-down list, the array of items to display, and the default item. In the following code sample, by defaultWednesday is displayed. Invoke add() to add the drop-down list to the screen.String choices[] ={"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};int iSetTo = 2;add(new ObjectChoiceField("First Drop-down List",choices,iSetTo));5. In the screen constructor, create a second drop-down list that displays a list of numbers by using theNumericChoiceField class. In the NumericChoiceField constructor, specify the label for the drop-down list, thefirst and last number to display in the drop-down list, the increment to use for the list of numbers, and the default number.In the following code sample, the numeric parameters are stored in int objects. The numbers 1 to 31 are included in thedrop-down list and by default the number 10 is displayed. Invoke add() to add the second drop-down list to the screen.int iStartAt = 1;int iEndAt = 31;int iIncrement = 1;iSetTo = 10;add(new NumericChoiceField("Numeric Drop-DownList",iStartAt,iEndAt,iIncrement,iSetTo));6. To override the default functionality that prompts the user to save changes before the application closes, in the extensionof the MainScreen class, override the MainScreen.onSavePrompt() method. In the following code sample, thereturn value is true which indicates that the application does not prompt the user before closing.public boolean onSavePrompt(){return true;}Development Guide Drop-down lists76
  • Code sample: Creating a drop-down listimport net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;public class MyUi extends UiApplication{public static void main(String[] args){MyUi theApp = new MyUi();theApp.enterEventDispatcher();}public MyUi(){pushScreen(new MyUiScreen());}}class MyUiScreen extends MainScreen{public MyUiScreen(){setTitle("UI Component Sample");String choices[] ={"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};int iSetTo = 2;add(new ObjectChoiceField("First Drop-down List",choices,iSetTo));int iStartAt = 1;int iEndAt = 31;int iIncrement = 1;iSetTo = 10;add(new NumericChoiceField("Numeric Drop-DownList",iStartAt,iEndAt,iIncrement,iSetTo));}public boolean onSavePrompt(){return true;}}LabelsUse a label to display text that identifies a control.Development Guide Labels77
  • Best practice: Implementing labels• Use the LabelField class to create labels.• Use clear, concise labels.• Group and order labels logically (for example, group related items together or include the most common items first). Avoidordering values alphabetically; alphabetical order is language specific.• Punctuate the label with a colon (:).Create a text label1. Import the net.rim.device.api.ui.component.LabelField class.2. Create an instance of a LabelField to add a text label to a screen.LabelField title = new LabelField("UI Component Sample", LabelField.ELLIPSIS);Lists and tablesUse lists and tables to display items that users can highlight and open. If the list is long, items are fetched and displayed inbatches. When users reach the last item in the list, the next batch of items displays at the end of the list.Use a simple list to easily display text in rows.Development Guide Lists and tables78
  • Use a rich list to easily display rows of text and icons. Currently, rich lists only display information and are not interactive.If you want to present items in columns and rows, use a table.Development Guide Lists and tables79
  • You can group items under headers to help users navigate through long lists. For example, you can create headers that collapse,making it easier for users to find items in the list.You can also group items under headers that always appear at the top of the list. For example, you can add a date as a headerand group messages received on that date under the header. Users can highlight a header to perform an action on the group ofitems or they can use shortcut keys to move through the list.Users can perform the following actions in lists and tables:Action BlackBerry devices with a trackpad onlyBlackBerry devices with a touch screenand a trackpadScroll through items in the list. Move a finger vertically on the trackpad. • Drag a finger vertically on the screen.• Swipe up or down on the screen.Development Guide Lists and tables80
  • Action BlackBerry devices with a trackpad onlyBlackBerry devices with a touch screenand a trackpad• Move a finger vertically on thetrackpad.Highlight an item in the list. Move a finger vertically on the trackpad. • Touch the item lightly.• Move a finger vertically on thetrackpad.Open an item in the list. • Click the trackpad.• Press the Enter key.• Tap the item.• Click the trackpad.• Press the Enter key.Best practice: Implementing lists and tables• Use the SimpleList class to create a list with text. Use the RichList class to create a display-only list with text andicons. Use the TableView class to create an interactive rich list with text and icons.• Use the TableView class to create a table with rows and columns. You can use the GridFieldManager if the numberof rows and columns in the table are fixed.• If the list is long and you want to display the items on separate screens, include Next and Previous buttons at the bottomof the screen. Alternatively, if the list is very long (for example, thousands of items), provide screen numbers instead.• If you expect users to move through the items in the list (for example, in a message list or a feed), assign shortcut keys formoving to the next or previous item in the list. Where possible, in English, allow users to press "N" to move to the next itemin the list and "P" to move to the previous item in the list.Create a list boxUse a list box to display a list from which users can select one or more values.1. Import the following classes:import net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;import java.util.Vector;2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher(), to enable the application to receive events. In the constructor, invokepushScreen, to display the custom screen for the application. The CreateMenuScreen class represents the customscreen which is described in step 3.Development Guide Lists and tables81
  • public class ListFields extends UiApplication{public static void main(String[] args){ListFields theApp = new ListFields();theApp.enterEventDispatcher();}public ListFields(){pushScreen(new ListFieldScreen());}}3. Create the custom screen for the application by extending the MainScreen class. In the constructor, invoke setTitle(), to display the title for the screen. Invoke add(), to display a text field on the screen. Invoke addMenuItem(), to adda menu item to the menu that MainScreen creates.class ListFieldScreen extends MainScreen{private ListField _listField;private Vector _listElements;public ListFieldScreen(){setTitle("List Field Sample");}}4. In the screen constructor, create the list box. Create an array for the items that you want to add to the list box by using theVector class. Create the list box by using the ListField() class. Invoke add(), to add the list box to the screen. InvokeinitializeList(), which is described in step 4, to add build the list box._listElements = new Vector();_listField = new ListField();ListCallback _callback = new ListCallback();_listField.setCallback(_callback);add(_listField);initializeList();5. Create a method to specify the items that you want to appear in the list box by using the String object. InvokeaddElement() to add the items to the list. Invoke setSize(), to specify the number of items in the list box.private void initializeList(){String itemOne = "List item one";String itemTwo = "List item two";_listElements.addElement(itemOne);_listElements.addElement(itemTwo);reloadList();}private void reloadList()Development Guide Lists and tables82
  • {_listField.setSize(_listElements.size());}6. Create a class that implements the ListFieldCallback interface. Implement drawListRow(), to add the list boxitems to the screen. Implement get(), to return the list box item at the specified index. Implement indexOfList(), toreturn the first occurrence of a given string. Implement getPreferredWidth(), to retrieve the width of the list box.private class ListCallback implements ListFieldCallback{public void drawListRow(ListField list, Graphics g, int index, int y, int w){String text = (String)_listElements.elementAt(index);g.drawText(text, 0, y, 0, w);}public Object get(ListField list, int index){return _listElements.elementAt(index);}public int indexOfList(ListField list, String prefix, int string){return _listElements.indexOf(prefix, string);}public int getPreferredWidth(ListField list){return Display.getWidth();}}Radio buttonsUse radio buttons to indicate a set of mutually exclusive but related choices.Users can perform the following action with radio buttons:Action BlackBerry devices with a trackpad onlyBlackBerry devices with a touch screenand a trackpadSelect a radio button. Press the Space key or click the trackpad. • Tap the item.• Press the Space key.• Click the trackpad.Development Guide Radio buttons83
  • Best practice: Implementing radio buttons• Use radio buttons for two or more choices when space is not an issue. If space is an issue, consider using a drop-down listinstead.• Use the RadioButtonField class to create radio buttons.• Verify that the content for radio buttons remains static. Content for radio buttons should not change depending on thecontext.• Do not start an action when users select a radio button. For example, do not open a new screen.• Align radio buttons vertically.• Group and order values logically (for example, group related radio buttons together or include the most common valuesfirst). Avoid ordering radio buttons alphabetically; alphabetical order is language specific.Guidelines for labels• Use clear, concise labels. Verify that the label clearly describes what occurs when users select the radio button. If the labelsare too long, they wrap.• Place labels on the right side of radio buttons.• Use sentence case capitalization.• Do not use end punctuation.Create a radio buttonYou can create a group of radio buttons by using the RadioButtonGroup class. A user can select only one option from a groupof radio buttons.1. Import the required classes and interfaces.import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;Development Guide Radio buttons84
  • 2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor,invoke pushScreen() to display the custom screen for the application. The MyUiScreen class, which is described instep 3, represents the custom screen.public class MyUi extends UiApplication{public static void main(String[] args){MyUi theApp = new MyUi();theApp.enterEventDispatcher();}public MyUi(){pushScreen(new MyUiScreen());}}3. Create the custom screen for the application by extending the MainScreen class. In the screen constructor, invokesetTitle() to specify the title for the screen.class MyUiScreen extends MainScreen{public MyUiScreen(){setTitle("UI Component Sample");}}4. Inthescreenconstructor,createagroupofradiobuttonsbyusingtheRadioButtonGroup class.Createtheradiobuttonsthat you want to add to the group by using the RadioButtonField class. In the RadioButtonField constructor,specify the label for the radio button, the group, and a Boolean value to indicate the default selection (for example,trueindicates that by default the radio is selected). Invoke add() to add the radio buttons to the screen.RadioButtonGroup rbg = new RadioButtonGroup();add(new RadioButtonField("Option 1",rbg,true));add(new RadioButtonField("Option 2",rbg,false));5. To override the default functionality that prompts the user to save changes before the application closes, in the extensionof the MainScreen class, override the MainScreen.onSavePrompt() method. In the following code sample, thereturn value is true which indicates that the application does not prompt the user before closing.public boolean onSavePrompt(){return true;}Development Guide Radio buttons85
  • Code sample: Creating a radio buttonimport net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;public class MyUi extends UiApplication{public static void main(String[] args){MyUi theApp = new MyUi();theApp.enterEventDispatcher();}public MyUi(){pushScreen(new MyUiScreen());}}class MyUiScreen extends MainScreen{public MyUiScreen(){setTitle("UI Component Sample");RadioButtonGroup rbg = new RadioButtonGroup();add(new RadioButtonField("Option 1",rbg,true));add(new RadioButtonField("Option 2",rbg,false));}public boolean onSavePrompt(){return true;}}Activity indicators and progress indicatorsActivity indicators and progress indicators show users that their BlackBerry® devices are performing an action, such as searchingfor items or removing languages.Use an activity indicator if you want to show that the BlackBerry® device is working and you cannot determine the duration ofthe action. You can add an activity indicator to any component, such as a screen, text field, or list item. You can also add text toan activity indicator to describe the action.Development Guide Activity indicators and progress indicators86
  • An activity indicator in a field An activity indicator with textUse a progress indicator if you can determine the duration of an action. Progress indicators include a label to indicate what theaction is and a horizontal bar that fills from left to right as the action progresses. A percentage appears in the bar to indicatehow much of the action is complete.Best practice: Implementing activity indicators and progress indicators• Always indicate progress when an action takes more than 2 seconds to complete.• Use a progress indicator when you can determine the duration of an action.• Use an activity indicator when you cannot determine the duration of an action.• Use the ActivityIndicatorView class to create activity indicators. Use the ProgressIndicatorView class tocreate progress indicators.• Provide useful progress information. For example, if users are downloading an application to their device, indicate thepercentage of data that their BlackBerry® device has downloaded. Be as accurate as possible with the progress information.Development Guide Activity indicators and progress indicators87
  • • Always allow users to use the End key to hide a progress indicator.Guidelines for text• Use a concise, descriptive text (for example, "Loading data..." or "Building an application list...").• If an action is long and you want to communicate what is happening at each stage, provide text that describes each stage(for example, "Downloading..." or "Installing...").• Use sentence case capitalization.• Punctuate the text with an ellipsis (...).Indicating activity or task progressYou can use the Activity and Progress Indicator API that is provided in thenet.rim.device.api.ui.component.progressindicator package to display visual cues on a screen to indicatethat work is being done or that a task is proceeding. You can represent an activity whose duration is unknown, as well as progressthat can be represented numerically (for example, as a percentage of a completed task).TheActivityandProgressIndicatorAPIusestheModel-View-Controllerdesignpatternandincludestwofieldsthatareresponsiblefor rendering the activity or progress:• The ActivityImageField class represents activity by using a bitmap that contains frames of an animation. Thedisplayed frame changes over time. Typically, this field is a spinner, an hourglass, or other similar animated visual cue. Thisfield is built and set by using the ActivityIndicatorView class.• The ProgressBarField class represents the progress of a task as a bar that fills as the task completes. This field is builtand set by using the ProgressIndicatorView class.TheProgressIndicatorDemosampleapplicationisincludedintheBlackBerry®Java®SDK.Thissampleapplicationdemonstrateshow to create and manipulate a variety of activity indicators and a progress indicator bar.Indicate activityYou can display a field in your BlackBerry® device application that indicates that work is proceeding. Typically, the field is aspinner,anhourglass,orothersimilaranimatedvisualcue.ThefieldisimplementedbyusingtheActivityImageField class.1. Import the required classes and interfaces.import net.rim.device.api.system.Bitmap;import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.progressindicator.*;import net.rim.device.api.ui.container.*;2. Create an image that contains frames of an animation and include it in your project. The image must consist of a series offramesoftheanimationarrangedhorizontally.Thewidthoftheimagemustbethewidthofaframemultipliedbythenumberof frames.For example, the following image has five frames of equal size.Development Guide Activity indicators and progress indicators88
  • 3. Create a bitmap from the image.Bitmap bitmap = Bitmap.getBitmapResource("spinner.png");4. Create an ActivityIndicatorView object. You can specify a style for the view in the constructor.ActivityIndicatorView view = new ActivityIndicatorView(Field.USE_ALL_WIDTH);To specify a manager to use for layout and focus, provide a second argument when you create theActivityIndicatorView. If you do not specify a manager, a VerticalFieldManager object is used.5. Create a model and a controller.ActivityIndicatorModel model = new ActivityIndicatorModel();ActivityIndicatorController controller = new ActivityIndicatorController();6. Connect the view, model, and controller.view.setController(controller);view.setModel(model);controller.setModel(model);controller.setView(view);model.setController(controller);7. Create the field that renders the activity from the bitmap.view.createActivityImageField(bitmap, 5, Field.FIELD_HCENTER);In this example, the bitmap consists of five frames and is displayed centered in the views manager.8. Add the view to your screen.add(view);9. Control the activity indication by controlling the views model, as needed.MenuItem _stopIndicator = new MenuItem("Stop spinner", 66000, 0){public void run(){view.getModel().cancel();}};MenuItem _resumeIndicator = new MenuItem("Resume spinner", 66010, 0){public void run(){Development Guide Activity indicators and progress indicators89
  • view.getModel().resume();}};This example invokes the models cancel() method to stop the animation. The example invokes the models resume() method to resume the animation.Code samplepublic class ActivityIndicatorScreen extends MainScreen{ActivityIndicatorView view = new ActivityIndicatorView(Field.USE_ALL_WIDTH);ActivityIndicatorModel model = new ActivityIndicatorModel();ActivityIndicatorController controller = new ActivityIndicatorController();public ActivityIndicatorScreen (){setTitle("Activity Indicator Demo");view.setController(controller);view.setModel(model);controller.setModel(model);controller.setView(view);model.setController(controller);// Define the indicator image and create a field from itBitmap bitmap = Bitmap.getBitmapResource("spinner.png");view.createActivityImageField(bitmap, 5, Field.FIELD_HCENTER);// add the view to the screenadd(view);MenuItem _stopIndicator = new MenuItem("Stop spinner", 66000, 0){public void run(){view.getModel().cancel();}};MenuItem _resumeIndicator = new MenuItem("Resume spinner", 66010, 0){public void run(){view.getModel().resume();}};addMenuItem(_stopIndicator);Development Guide Activity indicators and progress indicators90
  • addMenuItem(_resumeIndicator);}}The Progress Indicator Demo sample application that is included in the BlackBerry® Java® SDK creates and manipulates a varieyof activity indicators, including the spinner that is shown above.Indicate progressYou can display a field in your BlackBerry® device application that indicates that a task is proceeding. Progress is representedby a bar that fills as the task completes.1. Import the required classes and interfaces.import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;import net.rim.device.api.ui.component.progressindicator.*;2. Create a ProgressIndicatorView object. You can specify a style for the view in the constructor. In the followingexample, no style is specified.ProgressIndicatorView view = new ProgressIndicatorView(0);To specify a manager to use for layout and focus, provide a second argument when you create theProgressIndicatorView. If you do not specify a manager, a VerticalFieldManager object is used.3. Create a ProgressIndicatorController object.ProgressIndicatorController controller = new ProgressIndicatorController();4. CreateaProgressIndicatorModel object.Thisobjectrepresentstheprogressofthetask.Whenyoucreatetheobject,you can specify the models initial value, its maximum value, and its minimum value. ProgressIndicatorModel usesan Adjustment object to allow for threaded access to the data model and to allow the task to be represented by integervalues.ProgressIndicatorModel model = new ProgressIndicatorModel(0, 100, 0);In this example, the task starts with the value 0 and can reach 100. These values model the completion of a task as apercentage.5. Connect the controller, model, and view.model.setController(controller);view.setModel(model);view.setController(controller);controller.setModel(model);controller.setView(view);6. Create a thread to process the task. Typically, tasks that require progress indicators are performed by using a thread. Asthe task proceeds, update the value of the model to reflect the tasks progress.Development Guide Activity indicators and progress indicators91
  • class ProgressThread extends Thread{private boolean _paused;private boolean _stop;public void run(){// perform the task here and update the models value as appropriate}public synchronized void setPaused(boolean paused){// pause the indicator here}public synchronized void stopThread(){// stop the indicator here}}7. Create a class that Implements the ProgressIndicatorListener interface to be notified of changes to the datamodel. You can be notified when the model is reset, resumed, or cancelled, or when the the value of the model is changedby non-programmatic means.private final class DemoProgressIndicatorListener implementsProgressIndicatorListener{public void cancelled(){_progressThread.setPaused(true);}public void resumed(){_progressThread.setPaused(false);}...}8. Associate the listener with the model.model.addListener(new DemoProgressIndicatorListener());9. Set the label for the view. The label displays above the rendered ProgressIndicatorField (assuming that themanager is a VerticalFieldManager, which is the default manager).view.setLabel("Percent completion");Development Guide Activity indicators and progress indicators92
  • 10. Create the field that renders the progress. You can provide styles that are defined in ProgressBarField to specifywhether text is displayed on the bar and how it is displayed. By default, the models value is displayed in the center of thespace occupied by the bar.view.createProgressBar(Field.FIELD_HCENTER);In this example, the progress bar uses the default text style and is displayed centered in the views manager.11. Add the view to your screen.add(view);12. Control the progress indication by controlling the views model, as needed.MenuItem _pauseIndicator = new MenuItem("Pause indicator", 66010, 0){public void run(){view.getModel().cancel();}};MenuItem _resumeIndicator = new MenuItem("Resume indicator", 66020, 0){public void run(){view.getModel().resume();}};This example invokes the models cancel() method to stop the progress indication. The example invokes the modelsresume() method to resume progress indication.Code samplepublic class ProgressIndicatorScreen extends MainScreen{ProgressIndicatorView view = new ProgressIndicatorView(0);ProgressIndicatorModel model = new ProgressIndicatorModel(0, 100, 0);ProgressIndicatorController controller = new ProgressIndicatorController();ProgressThread _progressThread;public ProgressIndicatorScreen(){setTitle("Progress Indicator Screen");model.setController(controller);model.addListener(new DemoProgressIndicatorListener());view.setModel(model);view.setController(controller);controller.setModel(model);controller.setView(view);Development Guide Activity indicators and progress indicators93
  • view.setLabel("Percent completion");view.createProgressBar(Field.FIELD_HCENTER);add(view);MenuItem _startIndicator = new MenuItem("Start indicator", 66000, 0){public void run(){if(_progressThread != null){_progressThread.stopThread();}_progressThread = new ProgressThread();_progressThread.start();}};MenuItem _pauseIndicator = new MenuItem("Pause indicator", 66010, 0){public void run(){view.getModel().cancel();}};MenuItem _resumeIndicator = new MenuItem("Resume indicator", 66020, 0){public void run(){view.getModel().resume();}};addMenuItem(_startIndicator);addMenuItem(_pauseIndicator);addMenuItem(_resumeIndicator);}class ProgressThread extends Thread{private boolean _paused;private boolean _stop;public void run(){// Run dummy operations to simulate the processing of// a collection of data.for(int i = 0; i <= 100; ++i){synchronized(this)Development Guide Activity indicators and progress indicators94
  • {if(_stop){break;}if(_paused){try{wait();}catch(InterruptedException ie){}}}ProgressIndicatorScreen.this.model.setValue(i);try{// Simulate worksleep(250);}catch(InterruptedException ie){}}}public synchronized void setPaused(boolean paused){_paused = paused;this.notify();}public synchronized void stopThread(){_stop = true;if(_paused){// If the thread is in a paused state, wake it upthis.notify();}}}private final class DemoProgressIndicatorListener implementsProgressIndicatorListener{public void cancelled(){_progressThread.setPaused(true);}Development Guide Activity indicators and progress indicators95
  • public void resumed(){_progressThread.setPaused(false);}public void reset(){// Not implemented}public void setNonProgrammaticValue(int value){// Not implemented}public void configurationChanged(Adjustment source){// Not implemented}public void valueChanged(Adjustment source){// Not implemented}}}The Progress Indicator Demo sample application that is included in the BlackBerry® Java® SDK creates and manipulates aprogress bar.PickersYou can use pickers to help users choose an item from a list easily.Type of picker DescriptionFile This picker allows users to browse for files on their BlackBerry® devices.Development Guide Pickers96
  • Type of picker DescriptionLocation This picker allows users to choose a location from a list that you define. For example, you canallow users to choose their GPS location or a previously selected location.Date This picker allows users to choose a specific day, month, or year. For example, you can allow usersto choose a month and year to specify when their credit card expires.Development Guide Pickers97
  • Type of picker DescriptionTime This picker allows users to choose a specific hour, minute, or second.Best practice: Implementing pickersUse the FilePicker, LocationPicker, and DateTimePicker classes to create pickers.Guidelines for file pickers• Specify a specific view to display the types of files that match the users goal. For example, if a user is browsing pictures,display pictures in the file picker.• Allow users to start browsing from an appropriate default folder if possible.Development Guide Pickers98
  • Create a date picker1. Import the required classes and interfaces.import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;import net.rim.device.api.ui.picker.*;import java.util.*;2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the constructor, invokepushScreen() to display the custom screen for the application. The DatePickScreen class represents the customscreen that is described in step 3.public class DatePick extends UiApplication{public static void main(String[] args){DatePick theApp = new DatePick();theApp.enterEventDispatcher();}public DatePick(){pushScreen(new DatePickScreen());}}3. Create the custom screen for the application by extending the MainScreen class. In the constructor, invoke setTitle() to display a title on the screen. Invoke add() to display a rich text field on the screen.class DatePickScreen extends MainScreen{public DatePickScreen(){setTitle("Date Picker Sample");add(new RichTextField("Trying Date Picker"));}}4. Add a section of code to the event queue of the application by invoking invokeLater(). Create a Runnable objectand pass it as a parameter to invokeLater(). Override run() in the definition of Runnable.class DatePickScreen extends MainScreen{public DatePickScreen(){setTitle("Date Picker Sample");add(new RichTextField("Trying Date Picker"));Development Guide Pickers99
  • UiApplication.getUiApplication().invokeLater(new Runnable(){public void run(){}});}}5. In run(), invoke DateTimePicker.getInstance() to return a DateTimePicker object. Invoke doModal() todisplay the date picker. Invoke getDateTime() to return a Calendar object that represents the date and time the userselects. Use getTime() to return the date and time as a Date object. Use Dialog.alert() to display the selecteddate and time.class DatePickScreen extends MainScreen{public DatePickScreen(){setTitle("Date Picker Sample");add(new RichTextField("Trying Date Picker"));UiApplication.getUiApplication().invokeLater(new Runnable(){public void run(){DateTimePicker datePicker = DateTimePicker.getInstance();datePicker.doModal();Calendar cal = datePicker.getDateTime();Date date = cal.getTime();Dialog.alert("You selected " + date.toString());}});}}Code sample: Creating a date pickerimport net.rim.device.api.ui.*;import net.rim.device.api.ui.picker.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;import net.rim.device.api.database.*;import net.rim.device.api.io.*;import java.util.*;public class DatePick extends UiApplication{public static void main(String[] args){Development Guide Pickers100
  • DatePick theApp = new DatePick();theApp.enterEventDispatcher();}public DatePick(){pushScreen(new DatePickScreen());}}class DatePickScreen extends MainScreen{public DatePickScreen(){setTitle("Date Picker Sample");add(new RichTextField("Trying Date Picker"));UiApplication.getUiApplication().invokeLater(new Runnable(){public void run(){DateTimePicker datePicker = DateTimePicker.getInstance();datePicker.doModal();Calendar cal = datePicker.getDateTime();Date date = cal.getTime();Dialog.alert("You selected " + date.toString());}});}}Create a file picker1. Import the required classes and interfaces.import net.rim.device.api.ui.*;import net.rim.device.api.ui.picker.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;import java.util.*;2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor,invoke pushScreen() to display the custom screen for the application. The FilePickScreen class represents thecustom screen that is described in step 3.public class FilePick extends UiApplication{public static void main(String[] args){Development Guide Pickers101
  • FilePick theApp = new FilePick();theApp.enterEventDispatcher();}public FilePick(){pushScreen(new FilePickScreen());}}3. Create the custom screen for the application by extending the MainScreen class. In the screen constructor, invokesetTitle() to specify a title for the screen. Invoke add() to add a label field to the screen.class FilePickScreen extends MainScreen{public FilePickScreen(){setTitle("File Picker Sample");add(new LabelField("Trying File Picker"));}}4. In the screen constructor, invoke invokeLater() to add a section of code to the event queue of the application. Createa Runnable object and pass it as a parameter to invokeLater().class FilePickScreen extends MainScreen{public FilePickScreen(){setTitle("File Picker Sample");add(new LabelField("Trying File Picker"));UiApplication.getUiApplication().invokeLater(new Runnable(){public void run(){}});}}5. Override run() in the definition of Runnable. In run(), invoke FilePicker.getInstance() to return aFilePicker object. Create a FilePickListener object, which is described in step 6. Invoke setListener() toregister the listener for the file picker. Invoke show() to display the file picker on the screen.class FilePickScreen extends MainScreen{public FilePickScreen(){setTitle("File Picker Sample");add(new LabelField("Trying File Picker"));Development Guide Pickers102
  • UiApplication.getUiApplication().invokeLater(new Runnable(){public void run(){FilePicker fp = FilePicker.getInstance();FilePickListener fileListener = new FilePickListener();fp.setListener(fileListener);fp.show();}});}}6. Invoke Dialog.alert to create a dialog box with a message that displays which file was selected. InvokeDialog.alert in a class that implements the FilePicker.Listener interface by overriding selectionDone(). The application calls selectionDone() when the user selects a file using the file picker.class FilePickListener implements FilePicker.Listener{public void selectionDone(String str){Dialog.alert("You selected " + str);}}Code sample: Creating a file pickerimport net.rim.device.api.ui.*;import net.rim.device.api.ui.picker.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;import net.rim.device.api.io.*;public class FilePick extends UiApplication{public static void main(String[] args){FilePick theApp = new FilePick();theApp.enterEventDispatcher();}public FilePick(){pushScreen(new FilePickScreen());}}class FilePickScreen extends MainScreen{public FilePickScreen()Development Guide Pickers103
  • {setTitle("File Picker Sample");add(new LabelField("Trying File Picker"));UiApplication.getUiApplication().invokeLater(new Runnable(){public void run(){FilePicker fp = FilePicker.getInstance();FilePickListener fileListener = new FilePickListener();fp.setListener(fileListener);fp.show();}});}}class FilePickListener implements FilePicker.Listener{public void selectionDone(String str){Dialog.alert("You selected " + str);}}SearchUsers can use the search field on the Home screen to search for items in any application on the device, including third-partyapplications.Thesearchcanalsoincludecontentthatisnotstoredonthedevice,suchasanorganizationsdatabaseorawebsite.Users can also use a search field in an application to search for items in that application. For example, users can search for anemail message in a message list, a song in the Media application, or a contact in the contact list. In some cases, you might wantto display search results from other applications.Development Guide Search104
  • In some applications, the search field appears on the screen. In other cases, search is available from the full menu, the pop-upmenu, or the toolbar. As users type text in a search field, display the search results. If a large number of search results is returned,you can allow users to narrow their search to a field or a group of fields. For example, if users search the message list, they canusethedrop-downlisttotherightofthesearchfieldtonarrowtheirsearchtotheTofieldortheSubjectfield.Formoreinformationabout adding a search field to your application, see the BlackBerry Java Application Integration Development Guide.Users can perform the following actions in a search field:Action BlackBerry devices with a trackpad onlyBlackBerry devices with a touch screenand a trackpadOpen a highlighted item in thesearch results.• Press the Enter key.• Click the trackpad.• Tap the screen.• Press the Enter key.• Click the trackpad.Display a pop-up menu withactions for a search result (forexample, call a contact)Click and hold the trackpad. • Touch and hold a search result on thescreen.• Click and hold the trackpad.You can register content in your application so that it can be included in search results. You can also register your applicationas a way for users to extend a search. For example, if users search for a song in the Media application and do not find the song,you can allow users to search your application as an alternative source of search results. For more information about registeringcontent or an application, see the BlackBerry Java Application Integration Development Guide.Best practice: Implementing search• Use the net.rim.device.api.unifiedsearch package to implement search capabilities.Development Guide Search105
  • • Beselectivewiththecontentthatyouregistertobeincludedinsearchresults.Onlyregistercontentthatprovidesmeaningfulsearch results for users.• Try to present the most relevant items at the beginning of the list of search results. For example, if users are looking for arestaurant that has several different locations, display the restaurant that is closest to the users location at the beginningof the list of search results.• In the search results, bold the text that matches the text that users type. This approach helps users see why each itemappears in the list of search results.• If users need to search for a word on a screen (for example, in a message or on a web page), use the term "Find" in the Menu.Implementing search fields• Set the default focus to the search field. When the search results appear, set the default focus to the first item in the list ofsearch results.• Use the term "Search" as hint text in the search field.• Do not make search fields case sensitive.• Place the search field below the title bar on an application screen.• Do not assign shortcut keys for a screen that includes a search field. If you want to use shortcut keys, provide alternativesearch functionality. For example, allow users to search for messages in a message list using the menu.Create a search fieldYou can create an application that uses the KeywordFilterField class, included in thenet.rim.device.api.ui.component package, to provide a UI field that consists of a single text input field and a list ofselectable elements. As users type text in a search field, the application filters the elements in the list that begin with the searchtext. For more information about using the KeywordFilterField class, see the Keyword Filter Field sample application,included with the BlackBerry® Java® Development Environment version 4.3.1 or later.1. Import the required classes and interfaces.import net.rim.device.api.collection.util.SortedReadableList;import net.rim.device.api.io.LineReader;import net.rim.device.api.ui.component.KeywordFilterField;import net.rim.device.api.ui.component.KeywordProvider;import java.io.InputStream;import java.lang.String;import java.util.Vector;2. Create variables. In the following code sample, CountryList extends the SortedReadableList class andimplements the KeywordProvider interface.private KeywordFilterField _keywordField;private CountryList _CountryList;private Vector _countries;3. To create a list of selectable text items, populate a vector with data from a text file._countries = getDataFromFile();4. Create an instance of a class that extends the SortedReadableList class.Development Guide Search106
  • _CountryList = newCountryList(StringComparator.getInstance(true),_countries);5. To specify the elements of the list, create a new instance of a KeywordFilterField object._keywordField = new KeywordFilterField();6. Invoke KeywordFilterField.setList()._keywordField.setList(_CountryList, _CountryList);7. Set a label for the input field of the KeywordFilterFIeld._keywordField.setLabel("Search: ");8. Create the main screen of the application and add a KeywordFilterField to the main screen.KeywordFilterDemoScreen screen = newKeywordFilterDemoScreen(this,_keywordField);screen.add(_keywordField.getKeywordField());screen.add(_keywordField);pushScreen(screen);9. To create a method that populates and returns a vector of Country objects containing data from text file, in the methodsignature, specify Vector as the return type.public Vector getDataFromFile()10. Create and store a reference to a new Vector object.Vector countries = new Vector();11. Create an input stream to the text file.InputStream stream =getClass().getResourceAsStream("/Data/CountryData.txt");12. Read CRLF delimited lines from the input stream.LineReader lineReader = new LineReader(stream);13. Read data from the input stream one line at a time until you reach the end of file flag. Each line is parsed to extract datathat is used to construct Country objects.for(;;){//Obtain a line of text from the text fileString line = new String(lineReader.readLine());//If we are not at the end of the file, parse the line of textif(!line.equals("EOF")) {int space1 = line.indexOf(" ");String country = line.substring(0,space1);int space2 = line.indexOf(" ",space1+1);String population = line.substring(space1+1,space2);String capital = line.substring(space2+1,line.length());Development Guide Search107
  • // Create a new Country objectcountries.addElement(new Country(country,population,capital));}else {break;}} // end the for loopreturn countries;14. To add a keyword to the list of selectable text items, invoke SortedReadableList.doAdd(element).SortedReadableList.doAdd(((Country)countries.elementAt(i)).getCountryName()) ;15. To update the list of selectable text items, invoke KeywordFilterField.updateList()._keywordField.updateList();16. To obtain the key word that a BlackBerry device user typed into the KeywordFilterField, invokeKeywordFilterField.getKeyword().String userTypedWord = _keywordField.getKeyword();Autocomplete text fieldYou can use an autocomplete text field to predict what a BlackBerry® device user wants to type, and display a word or phrasebefore the user types it completely.When you create an AutoCompleteField object, you must associate a BasicFilteredList object with it. TheBasicFilteredList maintains references to data objects that are compared with to produce the list of words and phrases.You can configure which fields in the data objects are compared with and which fields are displayed when a match is found. Forexample, you can compare the text that the user types with the value of the DATA_FIELD_CONTACTS_BIRTHDAY field in theDATA_SOURCE_CONTACTS data source, and return the value of the correspondingDATA_FIELD_CONTACTS_NAME_FULL field.There are four types of data that you can bind to a BasicFilteredList to use with an AutoCompleteField.You can specify the set of strings to compare with in one of the following ways:• an array of literal strings• an array of objects that support toString()• data sources on a BlackBerry device, such as contacts, memos, tasks, and various types of media files• an array of objects and an array of strings with corresponding indexesBy default, the autocomplete text field displays the set of strings that is returned by the comparison process in a drop-down list.You can configure the appearance of this list by specifying style flags when you create the autocomplete text field. You canchange how the list appears and how users can interact with the list.Development Guide Search108
  • Create an autocomplete text field from a data set1. Import the required classes and interfaces.import net.rim.device.api.ui.UiApplication;import net.rim.device.api.ui.container.MainScreen;import net.rim.device.api.ui.component.AutoCompleteField;import net.rim.device.api.collection.util.*;2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the constructor, invokepushScreen() to display the custom screen for the application. The HomeScreen class, described in step 3, representsthe custom screen.public class AutoCompleteFieldApp extends UiApplication{public static void main(String[] args){AutoCompleteFieldApp app = new AutoCompleteFieldApp();app.enterEventDispatcher();}AutoCompleteFieldApp(){pushScreen(new HomeScreen());}}3. Create the custom screen by extending the MainScreen class.class HomeScreen extends MainScreen{public HomeScreen(){}}4. In the constructor, create a BasicFilteredList object. Create a String array and store the strings that you want tomatch against in the array. In this example, the strings are days of the week. Invoke addDataSet() to bind the data inthe array to the BasicFilteredList.BasicFilteredList filterList = new BasicFilteredList();String[] days ={"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};filterList.addDataSet(1,days,"days",BasicFilteredList.COMPARISON_IGNORE_CASE);5. In the constructor, create an AutoCompleteField object. Pass an instance of the BasicFilteredList to theAutoCompleteField constructor to bind the BasicFilteredList to the autocomplete text field. Invoke add() toadd the field to the screen.Development Guide Search109
  • AutoCompleteField autoCompleteField = newAutoCompleteField(filterList);add(autoCompleteField);Code sample: Creating an autocomplete field from a data setimport net.rim.device.api.ui.UiApplication;import net.rim.device.api.ui.container.MainScreen;import net.rim.device.api.ui.component.AutoCompleteField;import net.rim.device.api.collection.util.*;public class AutoCompleteFieldApp extends UiApplication{public static void main(String[] args){AutoCompleteFieldApp app = new AutoCompleteFieldApp();app.enterEventDispatcher();}AutoCompleteFieldApp(){HomeScreen scr = new HomeScreen();this.pushScreen(scr);}}class HomeScreen extends MainScreen{public HomeScreen(){BasicFilteredList filterList = new BasicFilteredList();String[] days = {"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};filterList.addDataSet(1,days,"days",BasicFilteredList.COMPARISON_IGNORE_CASE);AutoCompleteField autoCompleteField = new AutoCompleteField(filterList);add(autoCompleteField);}}Create an autocomplete text field from a data source1. Import the required classes and interfaces.import net.rim.device.api.ui.UiApplication;import net.rim.device.api.ui.container.MainScreen;import net.rim.device.api.ui.component.AutoCompleteField;import net.rim.device.api.collection.util.*;Development Guide Search110
  • 2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor,invoke pushScreen() to display the custom screen for the application. The HomeScreen class represents the customscreen that is described in step 3.public class AutoCompleteFieldApp extends UiApplication{public static void main(String[] args){AutoCompleteFieldApp app = new AutoCompleteFieldApp();app.enterEventDispatcher();}public AutoCompleteFieldApp(){pushScreen(new HomeScreen());}}3. Create the custom screen for the application by extending the MainScreen class.class HomeScreen extends MainScreen{public HomeScreen(){}}4. In the screen constructor, create a BasicFilteredList object. Invoke addDataSource() to bind a data source tothe BasicFilteredList. In this example, the data is contact information and the data source is the contact list. Thefirst argument that you pass to addDataSource() is a unique ID. The second argument binds theBasicFilteredList object to a data source. The third argument specifies the set of data source fields to compare with.The fourth argument specifies the set of data source fields to make available when a match is found. In this example, thefields to compare with are the same as the fields to make available when a match is found. The fifth argument specifies theprimary display field. The sixth argument specifies the secondary display field and is set to -1 if you do not want to use it.The final argument specifies a name for the BasicFilteredList; its value is generated automatically if you specifynull.BasicFilteredList filterList = new BasicFilteredList();filterList.addDataSource(1,BasicFilteredList.DATA_SOURCE_CONTACTS,BasicFilteredList.DATA_FIELD_CONTACTS_NAME_FULL |BasicFilteredList.DATA_FIELD_CONTACTS_COMPANY |BasicFilteredList.DATA_FIELD_CONTACTS_EMAIL,BasicFilteredList.DATA_FIELD_CONTACTS_NAME_FULL |BasicFilteredList.DATA_FIELD_CONTACTS_COMPANY |BasicFilteredList.DATA_FIELD_CONTACTS_EMAIL,Development Guide Search111
  • BasicFilteredList.DATA_FIELD_CONTACTS_NAME_FULL,-1,null);5. In the screen constructor, create an AutoCompleteField object. Pass the BasicFilteredList object that youcreated in step 4 to the AutoCompleteField constructor to bind the BasicFilteredList to the autocomplete textfield. Invoke add() to add the field to the screen.AutoCompleteField autoCompleteField = newAutoCompleteField(filterList);add(autoCompleteField);Code sample: Creating an autocomplete field from a data sourceimport net.rim.device.api.ui.UiApplication;import net.rim.device.api.ui.container.MainScreen;import net.rim.device.api.ui.component.AutoCompleteField;import net.rim.device.api.collection.util.*;public class AutoCompleteFieldApp extends UiApplication{public static void main(String[] args){AutoCompleteFieldApp app = new AutoCompleteFieldApp();app.enterEventDispatcher();}AutoCompleteFieldApp(){HomeScreen scr = new HomeScreen();this.pushScreen(scr);}}class HomeScreen extends MainScreen{public HomeScreen(){BasicFilteredList filterList = new BasicFilteredList();filterList.addDataSource(1,BasicFilteredList.DATA_SOURCE_CONTACTS,BasicFilteredList.DATA_FIELD_CONTACTS_NAME_FULL |BasicFilteredList.DATA_FIELD_CONTACTS_COMPANY |BasicFilteredList.DATA_FIELD_CONTACTS_EMAIL,BasicFilteredList.DATA_FIELD_CONTACTS_NAME_FULL |BasicFilteredList.DATA_FIELD_CONTACTS_COMPANY |BasicFilteredList.DATA_FIELD_CONTACTS_EMAIL,BasicFilteredList.DATA_FIELD_CONTACTS_NAME_FULL,BasicFilteredList.DATA_FIELD_CONTACTS_NAME_FULL,null);Development Guide Search112
  • AutoCompleteField autoCompleteField = new AutoCompleteField(filterList);add(autoCompleteField);}}Using data sources and fields with an autocomplete text fieldYou can use the AutoCompleteField class and the BasicFilteredList class to compare the text that a user types inan autocomplete text field with the values of fields in a specified data source. You specify the fields to use and their data sourcesby using a BasicFilteredList object that you pass as an argument to the constructor of the AutoCompleteField class.Data source FieldsDATA_SOURCE_APPOINTMENTS • DATA_FIELD_APPOINTMENTS_ALL• DATA_FIELD_APPOINTMENTS_ATTENDEES• DATA_FIELD_APPOINTMENTS_ORGANIZER• DATA_FIELD_APPOINTMENTS_SUBJECTDATA_SOURCE_CONTACTS • DATA_FIELD_CONTACTS_ADDRESS_ALL• DATA_FIELD_CONTACTS_ADDRESS_HOME• DATA_FIELD_CONTACTS_ADDRESS_WORK• DATA_FIELD_CONTACTS_ANNIVERSARY• DATA_FIELD_CONTACTS_BIRTHDAY• DATA_FIELD_CONTACTS_CATEGORIES• DATA_FIELD_CONTACTS_COMPANY• DATA_FIELD_CONTACTS_EMAIL• DATA_FIELD_CONTACTS_FAX• DATA_FIELD_CONTACTS_JOB_TITLE• DATA_FIELD_CONTACTS_NAME_FULL• DATA_FIELD_CONTACTS_NAME_FIRST• DATA_FIELD_CONTACTS_NAME_LAST• DATA_FIELD_CONTACTS_NOTES• DATA_FIELD_CONTACTS_PAGER• DATA_FIELD_CONTACTS_PHONE_ALL• DATA_FIELD_CONTACTS_PHONE_HOME• DATA_FIELD_CONTACTS_PHONE_HOME2• DATA_FIELD_CONTACTS_PHONE_MOBILEDevelopment Guide Search113
  • Data source Fields• DATA_FIELD_CONTACTS_PHONE_OTHER• DATA_FIELD_CONTACTS_PHONE_WORK• DATA_FIELD_CONTACTS_PHONE_WORK2• DATA_FIELD_CONTACTS_PINDATA_SOURCE_MEMOS • DATA_FIELD_MEMOS_TITLEDATA_SOURCE_MESSAGES • DATA_FIELD_MESSAGES_ALL• DATA_FIELD_MESSAGES_RECIPIENT• DATA_FIELD_MESSAGES_SENDER• DATA_FIELD_MESSAGES_SUBJECTDATA_SOURCE_MUSIC • DATA_FIELD_MUSIC_ALL• DATA_FIELD_MUSIC_ALBUM• DATA_FIELD_MUSIC_ARTIST• DATA_FIELD_MUSIC_GENRE• DATA_FIELD_MUSIC_PLAYLIST• DATA_FIELD_MUSIC_SONGDATA_SOURCE_PICTURES • DATA_FIELD_PICTURES_TITLEDATA_SOURCE_RINGTONES • DATA_FIELD_RINGTONES_TITLEDATA_SOURCE_TASKS • DATA_FIELD_TASKS_TITLEDATA_SOURCE_VIDEOS • DATA_FIELD_VIDEOS_TITLEDATA_SOURCE_VOICENOTES • DATA_FIELD_VOICENOTES_TITLESpin boxesUse a spin box to allow users to choose an item from an ordered list easily. For example, use spin boxes to allow users to find anumber or to change the day of the week.Action BlackBerry devices with a trackpad onlyBlackBerry devices with a touch screenand a trackpadFind an item in the list. Move a finger vertically on the trackpad. • Drag a finger vertically on the screen.• Swipe up or down on the screen.Development Guide Spin boxes114
  • Action BlackBerry devices with a trackpad onlyBlackBerry devices with a touch screenand a trackpad• Move a finger vertically on thetrackpad.Move a finger up or down on the screen orthe trackpad.Choose an item from the list. Click the trackpad. • Lift a finger from the screen.• Click the trackpad.Move to another spin box. Move a finger vertically on the trackpad. • Drag a finger vertically on the screen.• Move a finger vertically on thetrackpad.Create a spin box1. Import the required classes and interfaces.import net.rim.device.api.ui.UiApplication;import net.rim.device.api.ui.component.Dialog;import net.rim.device.api.ui.component.TextSpinBoxField;import net.rim.device.api.ui.container.MainScreen;import net.rim.device.api.ui.container.SpinBoxFieldManager;2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor,invoke pushScreen() to display the custom screen for the application. The HomeScreen class represents the customscreen that is described in step 3.Development Guide Spin boxes115
  • public class SpinBoxApp extends UiApplication{public static void main(String[] args){SpinBoxApp app = new SpinBoxApp();app.enterEventDispatcher();}public SpinBoxApp(){pushScreen(new HomeScreen());}}3. Create the custom screen for the application by extending the MainScreen class. Declare a variable for each field in thespin box and declare a variable for the spin box field manager.class HomeScreen extends MainScreen{TextSpinBoxField spinBoxDays;TextSpinBoxField spinBoxMonths;SpinBoxFieldManager spinBoxMgr;public HomeScreen(){}}4. In the screen constructor, create an array of String objects for each of the spin box fields.final String[] DAYS ={"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};final String[] MONTHS ={"January","February","March","April","May","June","July","August","September","October","November","December"};5. Inthescreenconstructor,createnewinstancesofthespinboxfieldmanagerandthetwospinboxfields.Passtheappropriatearray of strings as arguments to each of the spin box field constructors.spinBoxMgr = new SpinBoxFieldManager();spinBoxDays = new TextSpinBoxField(DAYS);spinBoxMonths = new TextSpinBoxField(MONTHS);6. In the screen constructor, add the spin box fields to the spin box field manager. Invoke add() to add the manager, andthe fields that it contains, to the screen.spinBoxMgr.add(spinBoxDays);spinBoxMgr.add(spinBoxMonths);add(spinBoxMgr);Development Guide Spin boxes116
  • Code sample: Creating a spin boximport net.rim.device.api.ui.UiApplication;import net.rim.device.api.ui.container.MainScreen;import net.rim.device.api.ui.container.SpinBoxFieldManager;import net.rim.device.api.ui.component.Dialog;import net.rim.device.api.ui.component.TextSpinBoxField;public class SpinBoxApp extends UiApplication{public static void main(String[] args){SpinBoxApp app = new SpinBoxApp();app.enterEventDispatcher();}public SpinBoxApp(){HomeScreen homeScreen = new HomeScreen();pushScreen(homeScreen);}}class HomeScreen extends MainScreen{TextSpinBoxField spinBoxDays;TextSpinBoxField spinBoxMonths;SpinBoxFieldManager spinBoxMgr;public HomeScreen(){final String[] DAYS ={"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};final String[] MONTHS ={"January","February","March","April","May","June","July","August","September","October","November","December"};spinBoxMgr = new SpinBoxFieldManager();spinBoxDays = new TextSpinBoxField(DAYS);spinBoxMonths = new TextSpinBoxField(MONTHS);spinBoxMgr.add(spinBoxDays);spinBoxMgr.add(spinBoxMonths);add(spinBoxMgr);}public void close(){Development Guide Spin boxes117
  • Dialog.alert("You selected " +(String)spinBoxDays.get(spinBoxDays.getSelectedIndex()) + " and " +(String)spinBoxMonths.get(spinBoxMonths.getSelectedIndex()));super.close();}}Best practice: Implementing spin boxes• Use spin boxes for a list of sequential items.• Use drop-down lists for non-sequential items or items with irregular intervals. For a short list of non-sequential items, youcan use a spin box to provide a more interactive experience for users.• Avoid using a spin box if several other components appear on the screen.• Use the SpinBoxField class and the SpinBoxFieldManager class to create spin boxes.• Add spin boxes to dialog boxes instead of screens where possible.• When users highlight a spin box, display three to five items vertically.• Use an identifiable pattern for the sequence of items (for example, 5, 10, 15) so that users can estimate how much they needto scroll to find the target item.• Avoid making users scroll horizontally to view multiple spin boxes. If necessary, separate spin boxes into multiple fields.• If the text in a spin box is too long, use an ellipsis (...).Text fieldsUsers can use a text field to type text.Type of text field Descriptionemail Users can insert an at sign (@) or a period (.) in an email address field by pressing the Space key.date and time Users can change the date or time on BlackBerry® devices with a trackpad using the keyboard or bymoving a finger vertically on the trackpad.Users can change the date or time on BlackBerry devices with a touch screen by swiping up or downon the screen.number When users need to type in a number field on a physical keyboard, the BlackBerry device switchesto number lock mode so that users do not need to press the Alt key to type numbers.When users need to type in a number field on a virtual keyboard, the number keyboard appears.password When users type in a password field, asterisks (*) appear instead of text. Users cannot cut, copy, orpaste text or use AutoText in password fields.Development Guide Text fields118
  • Type of text field DescriptionOn BlackBerry devices with SureType® technology, multi-tap is the default typing input method inpassword fields.phone number When users type in a phone number field on a physical keyboard, the BlackBerry device switches tonumber lock mode so that users do not need to press the Alt key to type numbers. You can also allowusers to perform the following actions in phone number fields:• Type the plus sign (+) for international phone numbers.• Type formatting characters such as the minus sign (-), period (.), parentheses (()), and spaces.• Type a number sign (#) or an asterisk (*).• Indicate a pause by typing a comma (,) or indicate a wait by typing an exclamation point (!).• Indicate an extension by pressing the Alt key and pressing E, X, or T.Whenusersneedtotypeinaphonenumberfieldonavirtualkeyboard,thenumberkeyboardappears.You can also allow users to perform the following actions in phone number fields:• Type a number sign (#) or an asterisk (*).• Indicate a pause or an extension by holding the asterisk (*) key.• Indicate a wait or an extension by holding the number sign (#) key.text In text fields, users type text. Users can cut, copy, and paste text in text fields. When the cursorreaches the end of a line of text, the text wraps to the next line.In text fields, BlackBerry devices can also turn telephone numbers, web pages, and email addressesinto links automatically.web address Users can insert a period (.) in an address field by pressing the Space key.Best practice: Implementing text fields• Use the TextField class to create text fields.• Choose a type of text field based on what you expect users to type. Using the most appropriate text field is important sothat the appropriate typing indicator appears on the screen when users type text. For example, when users type text in aphone number field, the number lock indicator appears in the upper-right corner of the screen. The field that you choosealso affects the default typing input method for the field on BlackBerry devices with SureType® technology.• Use or extend existing fields instead of creating custom fields where possible so that fields inherit the appropriate defaultbehavior.Development Guide Text fields119
  • • If necessary, include hint text to provide guidance to users. Use hint text if space on a screen is limited and you cannotinclude a label or instructional text. Hint text appears in the field and disappears when users type.Guidelines for labels• Use concise, descriptive labels. Avoid labels that wrap.• Use title case capitalization.• Punctuate labels for fields with a colon (:).• If you use hint text, keep it concise. Use sentence case capitalization.Creating a text fieldCreate a read-only text field that allows formatting1. Import the net.rim.device.api.ui.component.RichTextField class.2. Create an instance of a RichTextField.RichTextFieldrich=newRichTextField("RichTextField");Create an editable text field that has no formatting and accepts filters1. Import the following classes:• net.rim.device.api.ui.component.BasicEditField• net.rim.device.api.ui.component.EditField2. Create an instance of a BasicEditField.BasicEditFieldbf=newBasicEditField("BasicEditField:","",10,EditField.FILTER_UPPERCASE);Create an editable text field that allows special characters1. Import the net.rim.device.api.ui.component.EditField class.2. Create an instance of an EditField.EditField edit = new EditField("EditField: ", "", 10, EditField.FILTER_DEFAULT);Create a text field for AutoTextIf a text field supports AutoText, when users press the Space key twice, the BlackBerry® device inserts a period, capitalizes thenext letter after a period, and replaces words as defined in the AutoText application.1. Import the following classes:• net.rim.device.api.ui.component.AutoTextEditField• net.rim.device.api.ui.autotext.AutoTextDevelopment Guide Text fields120
  • • net.rim.device.api.ui.component.BasicEditField2. Create an instance of an AutoTextEditField.AutoTextEditField autoT = new AutoTextEditField("AutoTextEditField: ", "");Create a date field1. Import the required classes and interfaces.import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;import java.lang.*;2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor,invoke pushScreen() to display the custom screen for the application. The MyUiScreen class, which is described instep 3, represents the custom screen.public class MyUi extends UiApplication{public static void main(String[] args){MyUi theApp = new MyUi();theApp.enterEventDispatcher();}public MyUi(){pushScreen(new MyUiScreen());}}3. Create the custom screen for the application by extending the MainScreen class. In the screen constructor, invokesetTitle() to specify the title for the screen.class MyUiScreen extends MainScreen{public MyUiScreen(){setTitle("UI Component Sample");}}4. In the screen constructor, create a date field by using the DateField class. Provide System.currentTimeMillis() as a parameter to return the current time. Use the DateField.DATE_TIME style to display both the date and thetime. You can use other styles to display only the date or only the time.add(new DateField("Date: ", System.currentTimeMillis(),DateField.DATE_TIME));Development Guide Text fields121
  • Create a password field1. Import the net.rim.device.api.ui.component.PasswordEditField class.2. Create an instance of a PasswordEditField.For example, the following instance uses a constructor that lets you provide a default initial value for thePasswordEditField:PasswordEditField pwd = new PasswordEditField("PasswordEditField: ", "");Tree viewsUse a tree view to display objects, such as folders, in a hierarchical manner.Objects in the tree view are nodes. The highest node is the root node. A node in the tree can have child nodes under it. A nodethat has a child is a parent node.Users can perform the following action in a tree view:Action BlackBerry devices with a trackpad onlyBlackBerry devices with a touch screenand a trackpadExpand or collapse an objectwithaplussign(+)orminussign(-) in a hierarchy.Press the Space key or click the trackpad. • Tap the object.• Press the Space key.• Click the trackpad.Development Guide Tree views122
  • Best practice: Implementing tree views• Use the TreeField class to create tree views.• Provide a pop-up menu if users can perform multiple actions when they click a parent node.• Include a root node only if users need the ability to perform actions on the entire tree. Otherwise, exclude the root node.Create a field to display a tree viewUse a tree view to display objects, such as a folder structure, in a hierarchical manner. ATreeField contains nodes. The highestnode is the root node. A node in the tree can have child nodes under it. A node that has a child is a parent node.1. Import the required classes and interfaces.import net.rim.device.api.ui.component.TreeField;import net.rim.device.api.ui.component.TreeFieldCallback;import net.rim.device.api.ui.container.MainScreen;import java.lang.String;2. Implement the TreeFieldCallback interface.3. Invoke TreeField.setExpanded() on the TreeField object to specify whether a folder is collapsible. Create aTreeField object and multiple child nodes to the TreeField object. Invoke TreeField.setExpanded() usingnode4 as a parameter to collapse the folder.String fieldOne = new String("Main folder");...TreeCallback myCallback = new TreeCallback();TreeField myTree = new TreeField(myCallback, Field.FOCUSABLE);int node1 = myTree.addChildNode(0, fieldOne);int node2 = myTree.addChildNode(0, fieldTwo);int node3 = myTree.addChildNode(node2, fieldThree);int node4 = myTree.addChildNode(node3, fieldFour);...int node10 = myTree.addChildNode(node1, fieldTen);myTree.setExpanded(node4, false);...mainScreen.add(myTree);4. To repaint a TreeField when a node changes, create a class that implements the TreeFieldCallback interface andimplement the TreeFieldCallback.drawTreeItem method. The TreeFieldCallback.drawTreeItemmethod uses the cookie for a tree node to draw a String in the location of a node. TheTreeFieldCallback.drawTreeItem method invokes Graphics.drawText() to draw the String.private class TreeCallback implements TreeFieldCallback{public void drawTreeItem(TreeField _tree, Graphics g, int node, int y, intwidth, int indent){String text = (String)_tree.getCookie(node);Development Guide Tree views123
  • g.drawText(text, indent, y);}}Development Guide Tree views124
  • Images 9Using encoded imagesAccess an encoded image through an input stream1. Import the required classes.import java.io.InputStream;2. Save the image to the project folder or sub-folder.3. AddtheimagetotheprojectintheBlackBerry®Java®Plug-inEclipse®ortheBlackBerry®Java®DevelopmentEnvironment.4. Invoke getClass().getResourceAsStream() to retrieve the image as an input stream of bytes.private InputStream input;...Class _class = this.getClass();input = _class.getResourceAsStream("/images/example.png");Encode an image1. Import the required classes.import net.rim.device.api.system.EncodedImage;2. Invoke EncodedImage.createEncodedImage(). This method uses the unprocessed image data in the byte arrayto create an instance of EncodedImage.3. Check for an IllegalArgumentException, which EncodedImage.createEncodedImage() throws if the bytearray that you provide as a parameter does not contain a recognized image format.// Store the contents of the image file.private byte[] data = new byte[2430];try {// Read the image data into the byte arrayinput.read(data);} catch (IOException e) {// Handle exception.}try {EncodedImage image = EncodedImage.createEncodedImage(data, 0, data.length);} catch (IllegalArgumentException iae) {System.out.println("Image format not recognized.");}Development Guide Images125
  • Display an encoded image1. Import the required class.import net.rim.device.api.ui.component.BitmapField;2. Invoke BitmapField.setImage() to assign the encoded image to a BitmapField.3. Invoke add() to add the BitmapField to the screen.BitmapField field = new BitmapField();field.setImage(image);add(field);Specify the display size of an encoded image1. Import the required class.import net.rim.device.api.system.EncodedImage;2. Invoke EncodedImage.scaleImage32(intscaleX,intscaleY). The passed scale value parameters must benet.rim.device.api.math.Fixed32 numbers (0 < scale < 1 for upscaling, and scale > 1 for downscaling).scaleImage32() creates a new EncodedImage instead of modifying the current one.Specify the decoding mode for an image1. Import the required class.import net.rim.device.api.system.EncodedImage;2. Invoke EncodedImage.setDecodeMode() using one of the following modes as a parameter:• Use DECODE_ALPHA to decode an alpha channel, if one exists (this is the default mode).• UseDECODE_NATIVE toforcedecodingofthebitmapimagetothenativebitmapimagetypeoftheBlackBerry®DeviceSoftware.• Use DECODE_READONLY to mark the decoded bitmap image as read-only.Displaying an image for zooming and panningThe ZoomScreen class allows you to provide zoom and pan the functionality to an image. When a BlackBerry® device userclicks the trackball or touch screen, the screen displays the center region of the image zoomed in.When the image is zoomed in, the screen also displays an overlay highlighting the zoomed region. Scrolling the trackball orsliding a finger around the screen pans around the image. When the user stops panning and zooming the overlay disappearsfrom the screen.Development Guide Displaying an image for zooming and panning126
  • On BlackBerry devices with a touch screen, users can define the region of the image to zoom. The user can touch two points onthe image to define the diagonally opposite corners of the region. When the region is selected, teh user can move one fingeraround the image to move the zoom region. To zoom in on the defined region, the user clicks the screen. To zoom out, the userpresses the Escape key.Code sample: Displaying an image for zooming and panningimport net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.extension.container.*;public class ZoomableImageApp extends UiApplication{public static void main(String[] args){ZoomableImageApp theApp = new ZoomableImageApp();theApp.enterEventDispatcher();}public ZoomableImageApp(){EncodedImage myImg = EncodedImage.getEncodedImageResource("myImg.jpg");ZoomScreen zoomableImg = new ZoomScreen(myImg);pushScreen(zoomableImg);}}Display an image for zooming and panning1. Import the required classes and interfaces:import net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.extension.container.*;2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the constructor, create anEncodedImage using a resource in your project, create a ZoomScreen with the EncodedImage, and invokepushScreen() to display the image for zooming and panning.public class ZoomableImageApp extends UiApplication{public static void main(String[] args){ZoomableImageApp theApp = new ZoomableImageApp();Development Guide Displaying an image for zooming and panning127
  • theApp.enterEventDispatcher();}public ZoomableImageApp(){EncodedImage myImg = EncodedImage.getEncodedImageResource("myImg.jpg");ZoomScreen zoomableImg = new ZoomScreen(myImg);pushScreen(zoomableImg);}}Displaying a row of images for scrollingYou can use the PictureScrollField class to render a horizontal row of images that the user can scroll through by usingthe trackball or touch gestures.The PictureScrollField allows you to define the highlighting style of the selected image, the background style of thePictureScrollField, the text displayed below the selected image, the tooltip text that appears when an image is initiallyselected, and the height and width of the images.Code sample: Displaying a row of images for scrollingimport net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;import net.rim.device.api.ui.decor.*;import net.rim.device.api.ui.extension.component.*;public class PictureScrollFieldDemo extends UiApplication{public static void main(String[] args){PictureScrollFieldDemo app = new PictureScrollFieldDemo();app.enterEventDispatcher();}public PictureScrollFieldDemo(){pushScreen(new PictureScrollFieldDemoScreen());}}class PictureScrollFieldDemoScreen extends MainScreen{public PictureScrollFieldDemoScreen(){setTitle("PictureScrollField Demo");Development Guide Displaying a row of images for scrolling128
  • Bitmap[] images = new Bitmap[3];String[] labels = new String[3];String[] tooltips = new String[3];images[0] = Bitmap.getBitmapResource("img1.jpg");labels[0] = "Label for image 1";tooltips[0] = "Tooltip for image 1";images[1] = Bitmap.getBitmapResource("img2.jpg");labels[1] = "Label for image 2";tooltips[1] = "Tooltip for image 2";images[2] = Bitmap.getBitmapResource("img3.jpg");labels[2] = "Label for image 3";tooltips[2] = "Tooltip for image 3";ScrollEntry[] entries = ScrollEntry[3];for (int i = 0; i < entries.length; i++){entries[i] = new ScrollEntry(images[i], labels[i],tooltips[i]);}PictureScrollField pictureScrollField = new PictureScrollField(150, 100);pictureScrollField.setData(entries, 0);pictureScrollField.setHighlightStyle(HighlightStyle.ILLUMINATE);pictureScrollField.setHighlightBorderColor(Color.BLUE);pictureScrollField.setBackground(BackgroundFactory.createSolidTransparentBackground(Color.RED, 150));pictureScrollField.setLabelsVisible(true);add(pictureScrollField);}}Display a row of images for scrolling1. Import the required classes and interfaces.import net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;import net.rim.device.api.ui.decor.*;import net.rim.device.api.ui.extension.component.*;Development Guide Displaying a row of images for scrolling129
  • 2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the constructor, invokepushScreen() to display the custom screen for the application. The PictureScrollFieldDemoScreen class,described in step 3, represents the custom screen.public class PictureScrollFieldDemo extends UiApplication{public static void main(String[] args){PictureScrollFieldDemo app = new PictureScrollFieldDemo();app.enterEventDispatcher();}public PictureScrollFieldDemo(){pushScreen(new PictureScrollFieldDemoScreen());}}3. Create the framework for the custom screen by extending the MainScreen class.class PictureScrollFieldDemoScreen extends MainScreen{public PictureScrollFieldDemoScreen(){}}4. In the constructor, invoke setTitle() to set the text that appears in the title section of the screen.setTitle("PictureScrollField Demo");5. In the constructor, create and initialize three arrays to store the images to display in the PictureScrollField and thelabels and tooltip text that appear when each image is selected. In this example, the PictureScrollField containsthree images.Bitmap[] images = new Bitmap[3];String[] labels = new String[3];String[] tooltips = new String[3];images[0] = Bitmap.getBitmapResource("img1.jpg");labels[0] = "Label for image 1";tooltips[0] = "Tooltip for image 1";images[1] = Bitmap.getBitmapResource("img2.jpg");labels[1] = "Label for image 2";tooltips[1] = "Tooltip for image 2";images[2] = Bitmap.getBitmapResource("img3.jpg");labels[2] = "Label for image 3";tooltips[2] = "Tooltip for image 3";Development Guide Displaying a row of images for scrolling130
  • 6. In the constructor, create and initialize an array of ScrollEntry objects. A ScrollEntry represents each item in thePictureScrollField.ScrollEntry[] entries = ScrollEntry[3];for (int i = 0; i < entries.length; i++){entries[i] = new ScrollEntry(images[i], labels[i], tooltips[i]);}7. In the constructor, create and initialize the PictureScrollField with each image 150 pixels wide and 100 pixels high.Invoke setData() to set the entries in the PictureScrollField. The second paramater in setData() specifieswhich image position is selected by default.PictureScrollField pictureScrollField = new PictureScrollField(150,100);pictureScrollField.setData(entries, 0);8. In the constructor, set the style of the PictureScrollField. Invoke setHighlightStyle() to specify how theselected image is highlighted. Invoke setHighlightBorderColor() to specify the selected images border color.Invoke setBackground() to specify the background of the PictureScrollField. Invoke setLabelVisible() to specify whether the PictureScrollField displays the selected images label.pictureScrollField.setHighlightStyle(HighlightStyle.ILLUMINATE);pictureScrollField.setHighlightBorderColor(Color.BLUE);pictureScrollField.setBackground(BackgroundFactory.createSolidTransparentBackground(Color.RED, 150));pictureScrollField.setLabelsVisible(true);9. In the constructor, invoke add() to display the PictureScrollField.add(pictureScrollField);Development Guide Displaying a row of images for scrolling131
  • Menu items 10Create a menuThe MainScreen class provides standard components of a BlackBerry® device application. It includes a default menu.1. Import the required classes and interfaces.import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor,invoke pushScreen() to display the custom screen for the application. The CreateMenuScreen class, which isdescribed in step 3, represents the custom screen.public class CreateMenu extends UiApplication{public static void main(String[] args){CreateMenu theApp = new CreateMenu();theApp.enterEventDispatcher();}public CreateMenu(){pushScreen(new CreateMenuScreen());}}3. Create the custom screen for the application by extending the MainScreen class. In the screen constructor, invokesetTitle() to specify the title for the screen. Invoke add() to add a text field to the screen. Invoke addMenuItem() to add a menu item to the menu that MainScreen creates.class CreateMenuScreen extends MainScreen{public CreateMenuScreen(){setTitle("Create Menu Sample");add(new RichTextField("Create a menu"));addMenuItem(_viewItem);}}4. Create the menu item by using the MenuItem class. Override run() to specify the action that occurs when the user clicksthe menu item. When the user clicks the menu item, the application invokes Menu.run().Development Guide Menu items132
  • private MenuItem _viewItem = new MenuItem("More Info", 110, 10){public void run(){Dialog.inform("Display more information");}};5. Override close() to display a dialog box when the user clicks the Close menu item. By default, the Close menu item isincluded in the menu that MainScreen creates. Invoke super.close() to close the application. When the user closesthe dialog box, the application invokes MainScreen.close() to close the application.public void close(){Dialog.alert("Goodbye!");super.close();}Code sample: Creating a menuimport net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;public class CreateMenu extends UiApplication{public static void main(String[] args){CreateMenu theApp = new CreateMenu();theApp.enterEventDispatcher();}public CreateMenu(){pushScreen(new CreateMenuScreen());}}class CreateMenuScreen extends MainScreen{public CreateMenuScreen(){setTitle("Create Menu Sample");add(new RichTextField("Create a menu"));addMenuItem(_viewItem);}private MenuItem _viewItem = new MenuItem("More Info", 110, 10){public void run(){Dialog.inform("Display more information");}Development Guide Create a menu133
  • };public void close(){Dialog.alert("Goodbye!");super.close();}}Best practice: Implementing menus• Always provide a full menu.• MakesurethatuserscanpresstheMenukeytoopenthefullmenuandtoinitiateanactionwhenamenuitemishighlighted.Make sure that users can also hold the Menu key to open the dialog box for switching applications.• For the default menu item, use the menu item that users are most likely to select.• Place the default menu item and other common menu items in the middle of the menu.• Verify that the order of menu items is consistent with the order of menu items in other BlackBerry® device applications.• Groupmenuitemsaccordingtocommonusageorcommonfunctionality,andwherepossible,testyourgroupingswithusers.• Insert separators between menu item groupings.• Do not place menu items for conflicting actions close together. For example, do not place a "Delete" menu item beside an"Open" menu item.• Always include the "Switch application" and "Close" menu items. Place these menu items at the end of the menu. If youuse standard components, these menu items are included automatically.Guidelines for labels• Use concise, descriptive labels that are no longer than 12 characters. If a label is too long, an ellipsis (...) appears to indicatethat the text is truncated.• Use verbs for labels.• Use title case capitalization for labels.• Use an ellipsis in a menu item label to indicate that users must perform another action after they click the menu item. Forexample, if users click the Go To Date... menu item in the calendar, they must specify a date on the screen that appears.• Avoid using symbols such as an asterisk (*) in labels.SubmenusA submenu is a group of related menu items that appears as a subset of a menu item in the full menu. By including items in asubmenu, users can find frequently used items or important items more easily in the full menu. Submenus typically include thefollowing types of actions:• sending items in multiple ways (for example, sending a picture in an email message, an MMS message, or as an audiopostcard)• sorting, searching for, finding, and filtering items in different ways (for example, filtering messages by sender or subject)Development Guide Best practice: Implementing menus134
  • • changing views (for example, day, week, or agenda view in a calendar)Action BlackBerry devices with a trackpad onlyBlackBerry devices with a touch screenand a trackpadWhen a menu item ishighlighted in a full menu,display a submenu.• Click the trackpad.• Move a finger to the right on thetrackpad.• Press the Menu key.• Press the Enter key.• Tap the menu item.• Click the trackpad.• Move a finger to the right on thetrackpad.• Press the Menu key.• Press the Enter key.Choose a menu item from asubmenu.• Click the trackpad.• Press the Menu key.• Press the Enter key.• Tap the menu item.• Click the trackpad.• Press the Menu key.• Press the Enter key.Close a submenu. • Move a finger to the left on thetrackpad.• Press the Escape key.• Tap outside the submenu.• Move a finger to the left on thetrackpad.• Press the Escape key.Close a submenu and a fullmenu.Press the Escape key twice. • Tap outside the full menu and thesubmenu twice.• Press the Escape key twice.• Open or close the slider.An arrow appears when submenu items are available for an item in the full menu.Development Guide Submenus135
  • A full menu item with an arrow A full menu and a submenuBest practice: Implementing submenus• Use the Submenu subclass to create submenus.• Use submenus to reduce the number of menu items in the full menu. For example, if users have to scroll to see all the itemsin a full menu, group some of the menu items in a submenu.• Group related items in a submenu. For example, if "Sort By" appears in the full menu, group "Date," "Name," and "Subject"in a submenu.• Consider grouping advanced features in a submenu. For example, use "Additional Options" in the full menu and group theoptions in the submenu.• Avoid using submenus for only one or two menu items.• If a submenu includes more than six items, consider grouping the items into two sections in the submenu. Place the menuitemsthatarefrequentlyusedatthetopofthesubmenu,insertaseparator,andthenordertherestoftheitemsalphabetically.• If a menu item requires users to do more than click the item (for example, if a user has to specify a date), open a dialog box.• Avoid including frequently used menu items or important menu items in submenus.• Avoid implementing a submenu from a submenu.Guidelines for labels• In the full menu, use concise, descriptive labels that clearly define the action. Users should not have to open the submenuto understand the meaning of the item in the full menu.• In the full menu, use verbs for labels. Use nouns only if the meaning is clear. For example, if "Email Accounts" appears inthe full menu, group each email account in a submenu.• Avoid repeating verbs in submenus. For example, avoid using "Sort By" in the full menu and "Sort By Date" and "Sort ByName" in the submenu.• Use title case capitalization for labels. Capitalize the first word in the submenu even if it is a preposition. For example, use"Send" > "As Email" instead of "as Email").Development Guide Submenus136
  • • Avoid using the term "More" in the full menu unless the location of the menu item clearly indicates what "more" refers to.For example, if "Inbox," "Outbox," and "More" appear between separators in the full menu, group additional optionsassociated with a mailbox in a submenu.Create a submenuYou can create a submenu for your BlackBerry® device application. A submenu appears when a user selects a menu item thathas a submenu associated with it.1. Import the required classes and interfaces.import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor,invoke pushScreen() to display the custom screen for the application. The CreateSubmenuScreen class, which isdescribed in step 3, represents the custom screen.public class CreateSubmenu extends UiApplication{public static void main(String[] args){CreateSubmenu theApp = new CreateSubmenu();theApp.enterEventDispatcher();}public CreateSubmenu(){pushScreen(new CreateSubmenuScreen());}}3. Create the custom screen for the application by extending the MainScreen class. In the screen constructor, invokesetTitle() to specify the title for the screen. Invoke add() to add a text field to the screen.class CreateSubmenuScreen extends MainScreen{public CreateSubmenuScreen(){setTitle("Create Submenu Sample");add(new RichTextField("Create a submenu"));}}4. Create the submenu items by using the MenuItem class. For each submenu item, override run() to specify the actionthat occurs when the user clicks the menu item. When the user clicks the menu item, the application invokes Menu.run().private MenuItem _status1 = new MenuItem("Available", 100, 1){public void run()Development Guide Submenus137
  • {Dialog.inform("Im available");}};private MenuItem _status2 = new MenuItem("Unavailable", 200, 2){public void run(){Dialog.inform("Im unavailable");}};5. Override makeMenu() to create the menu for the application. Create the submenu by using the SubMenu class. Invokeadd() to add the submenu items to the submenu. Invoke super.makeMenu() to create the menu.protected void makeMenu( Menu menu, int instance ){SubMenu statusSubMenu = new SubMenu(null,"My Status",300,3);statusSubMenu.add(_status1);statusSubMenu.add(_status2);menu.add(statusSubMenu);super.makeMenu(menu, instance);};Code sample: Creating a submenuimport net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;public class CreateSubmenu extends UiApplication{public static void main(String[] args){CreateSubmenu theApp = new CreateSubmenu();theApp.enterEventDispatcher();}public CreateSubmenu(){pushScreen(new CreateSubmenuScreen());}}class CreateSubmenuScreen extends MainScreen{public CreateSubmenuScreen(){setTitle("Create Submenu Sample");add(new RichTextField("Create a submenu"));}private MenuItem _status1 = new MenuItem("Available", 100, 1)Development Guide Submenus138
  • {public void run(){Dialog.inform("Im available");}};private MenuItem _status2 = new MenuItem("Unavailable", 200, 2){public void run(){Dialog.inform("Im unavailable");}};protected void makeMenu( Menu menu, int instance ){SubMenu statusSubMenu = new SubMenu(null,"My Status",300,3);statusSubMenu.add(_status1);statusSubMenu.add(_status2);menu.add(statusSubMenu);super.makeMenu(menu, instance);};}Pop-up menusA pop-up menu provides users with a quick way to access the most common actions for a highlighted item. You can also use apop-up menu if a highlighted item has multiple actions associated with it or if a highlighted item does not have any primaryactions associated with it. You can create a pop-up menu that contains nine actions, six actions, or three actions.Action BlackBerry devices with a trackpad onlyBlackBerry devices with a touch screenand a trackpadOpen a pop-up menu. • Click the trackpad.• If a primary action has already beenassigned to an item (for example, opena message), users can click and holdthe trackpad to open a pop-up menu.• Tap the item.• Click the trackpad.• If a primary action has already beenassigned to an item (for example, openamessage),userscanclickandholdthetrackpad or touch and hold a finger onthe touch screen to open a pop-upmenu.Choose an item from a pop-upmenu.• Click the trackpad.• Press the Enter key.• Tap the item.• Click the trackpad.Development Guide Pop-up menus139
  • Action BlackBerry devices with a trackpad onlyBlackBerry devices with a touch screenand a trackpad• Press the Enter key.Close a pop-up menu. Press the Escape key. • Tap outside the pop-up menu.• Press the Escape key.• Open or close the slider.Pop-up menus replace context menus, or short menus. Any existing context menus are automatically converted into pop-upmenus.Best practice: Implementing pop-up menus• Use pop-up menus instead of context menus (short menus). Make sure that the pop-up menu provides value to users.• Set the menu item that users are most likely to choose as the default menu item. The default item in the pop-up menushould be the same as the default item in the full menu.• Only include the most common actions for a highlighted item in a pop-up menu.• Include an icon and a label for each item in the pop-up menu. Create icons with an average size of 33-by-33 pixels. Theseicons appear on a 60-by-40 pixel canvas and should have some negative space.Guidelines for placing items in pop-up menus• Place the default menu item in the center of the pop-up menu.• Order the rest of the items from most common to least common according to the numbered positions below. Try to leverageusers muscle memory by making the order of actions consistent with the order of actions in other BlackBerry® deviceapplications.Development Guide Pop-up menus140
  • • If the positions are filled dynamically, do not display menu items that are unavailable. Allow the available menu items toshift position.• If there are not enough actions to fill the menu, use a smaller menu. If one or two positions need to be filled, include usefulactions such as Copy or Search. If you do not fill a position, "Switch Application" or "Home" appears.About placing items in the pop-up menusPop-up menus display menu items in a 3-by-3, 3-by-2, or 3-by-1 grid depending on the number of items. By default, the pop-upmenu always includes an item to open the full menu. You can provide up to eight additional items. If you provide more than eightitems, the additional items are not displayed. You can add additional items to the full menu instead.The first item that you add to the vector of CommandItem elements is the default item in the pop-up menu. The default itemappears highlighted in the center of the grid when the BlackBerry® device user opens the pop-up menu. The other items arepositioned in the pop-up menu based on the order that you add them.If the number of items that you add to the pop-up menu leaves empty cells in the grid, filler items are added to the menu. Thefirst filler item is an option to switch applications. The second filler item is an option to return to the Home screen.Support for legacy context menusSince BlackBerry® Java® SDK 6.0, an applications context menu or short menu is converted to a pop-up menu. Whether youadded menu items to a context menu or used the items that were added to the context menu by default, you do not have tochange your code to have these items appear in the pop-up menu instead. However, BlackBerry Java SDK 6.0 includes classesand interfaces that you can use to build a pop-up menu, and allows you to use the Command Framework API and make yourDevelopment Guide Pop-up menus141
  • code more modular. For example, if your application has a UI component and a menu item that performs the same function, byusing the Command Framework API, you can write the code for that function once and use it throughout your application, aswell as make it available for other applications to use.A context menu item included an ordinal number which determined the placement of the item in the menu. The lower the ordinalnumber, the higher the position of the item in the menu. When a context menu is converted to a pop-up menu, the menu itemthat has the lowest ordinal number becomes the default pop-up menu item. The remaining items are added to the pop-up menufrom the lowest ordinal number to the highest. If an icon was associated with a menu item in your legacy context menu, it is usedfor the item in the pop-up menu. Otherwise, a default icon is used. Similar to other pop-up menus, only the first eight contextmenu items are displayed in the pop-up menu. If the context menu has more than eight menu items, make sure that you use theordinal numbers for the menu items appropriately so that the most important and useful items appear in the pop-up menu.For more information about creating context menus, visit the BlackBerry Developer Resource Center at www.blackberry.com/developer to read Distinguish between a full menu and a primary actions menu.Creating a pop-up menuYou can create a pop-up menu by using classes that are available in the net.rim.device.api.ui.menu package, and youcan define the functionality of the pop-up menu items by using the Command Framework API.A pop-up menu consists of a context menu provider, a command item provider, and command items.Component DescriptionContext menu provider You use the DefaultContextMenuProvider class to create and display ascreens pop-up menu. When a BlackBerry® device user opens a pop-up menu, thecontext menu provider looks for fields on the screen that are command itemproviders. DefaultContextMenuProvider is the default implementation ofContextMenuProvider. If you do not provide a screen with a context menuprovider, the legacy context menu is converted and displayed as a pop-up menu.Command item provider You use the CommandItemProvider class to configure a field on your UI screensothatthefieldcanprovidecontextandcommanditemstothepop-upmenubasedon the current context. For example, you could configure an email address as acommand item provider and provide the user with different actions based onwhether the email address is in the users contact list.Command items You use the CommandItem class to specify the text, icon, and behavior of a pop-up menu item. You define the behavior of the pop-up menu by using a command.The command acts as a proxy to an instance of a command handler, which definesthe functionality of the pop-up menu item. For example, for an email address, youDevelopment Guide Pop-up menus142
  • Component Descriptioncould provide command items to add or view a contact based on whether theselected email address appears in the users contact list. The command handlerwould contain the code to add or view the contact.For more information on commands and command handlers, see CommandFramework API. The Command Framework sample application that is provided inthe BlackBerry® Java® SDK demonstrates commands and command handlers.If you use a legacy context menu, BlackBerry® Device Software 6.0 converts the context menu items to command items andprovides them to the command item provider. For more information, see Support for legacy context menus.Create a pop-up menu1. Import the required classes and interfaces.import net.rim.device.api.command.*;import net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;import net.rim.device.api.ui.menu.*;import net.rim.device.api.ui.image.*;import net.rim.device.api.util.*;import java.util.*;2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor,invoke pushScreen() to display the custom screen for the application. The MyPopUpMenuScreen class, which isdescribed in step 3, represents the custom screen.public class MyPopUpMenuApp extends UiApplication{public static void main(String[] args){Mypop-upMenuApp theApp = new Mypop-upMenuApp();theApp.enterEventDispatcher();}public Mypop-upMenuApp(){pushScreen(new Mypop-upMenuScreen());}}3. Create the custom screen for the application by extending the MainScreen class. In the screen constructor, invokesetTitle() to specify the title for the screen.Development Guide Pop-up menus143
  • class MyPopUpMenuScreen extends MainScreen{EmailAddressEditField emailAddress;public Mypop-upMenuScreen(){setTitle("Pop-Up Menu Demo");}}4. In the screen constructor, specify a context menu provider. Pass a DefaultContextMenuProvider object toScreen.setContextMenuProvider() to enable your screen to display a pop-up menu.setContextMenuProvider(new DefaultContextMenuProvider());5. In the screen constructor, create UI components that can invoke the pop-up menu. In the following code sample, the labeluses the Field.FOCUSABLE property to allow users to highlight the field.LabelField labelField = new LabelField("Click to invoke pop-up menu",Field.FOCUSABLE);emailAddress = new EmailAddressEditField("Email address: ", "name@blackberry.com",40);6. In the screen constructor, configure the UI components as command item providers. TheDefaultContextMenuProvider object looks for fields that are configured as command item providers, and uses themto create and display a pop-up menu. For each component, invoke Field.setCommandItemProvider() to configurethe field as a command item provider. The ItemProvider class is described in step 7.ItemProvider itemProvider = new ItemProvider();labelField.setCommandItemProvider(itemProvider);emailAddress.setCommandItemProvider(itemProvider);7. In the custom screen, implement the CommandItemProvider interface. In getContext(), return the field that isconfigured as a command item provider. In getItems(), create a Vector object to add the pop-up menu items to.class ItemProvider implements CommandItemProvider{public Object getContext(Field field){return field;}public Vector getItems(Field field){}}8. In getItems(), provide the pop-up menu items by creating instances of the CommandItem class. For each commanditem, specify the pop-up menu text, icon, and command. In the following code sample, an if-then-else statement isused to check which component invoked the pop-up menu before creating the CommandItem. The command is a proxyto an instance of a class that extends the abstract CommandHandler class, which is described in step 9. InvokeVector.addElement() to add the pop-up menu items to the Vector. Return the Vector.Development Guide Pop-up menus144
  • CommandItem defaultCmd;Image myIcon = ImageFactory.createImage(Bitmap.getBitmapResource("my_logo.png"));if(field.equals(emailAddress)){defaultCmd = new CommandItem(new StringProvider("Email Address"), myIcon, newCommand(new DialogCommandHandler()));}else {defaultCmd = new CommandItem(new StringProvider("Label Field"), myIcon, newCommand(new DialogCommandHandler()));}items.addElement(defaultCmd);return items;9. In the custom screen, create a command handler by creating a class that extends the abstract CommandHandler class.In execute(), define the functionality that you want to associate with the pop-up menu items. This command handlercouldbeusedbyanyUIcomponentonyourscreen(forexample,fullmenuitems,buttons,andsoon).BecausecanExecute() is not implemented, this command is always executable. In the following code sample, a dialog box appears when theuser clicks a pop-up menu item.class DialogCommandHandler extends CommandHandler{public void execute(ReadOnlyCommandMetadata metadata, Object context){Dialog.alert("Executing command for " + context.toString());}}Code sample: Creating a pop-up menuimport net.rim.device.api.command.*;import net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;import net.rim.device.api.ui.menu.*;import net.rim.device.api.ui.image.*;import net.rim.device.api.util.*;import java.util.*;public class MyPopUpMenuApp extends UiApplication{public static void main(String[] args){MyPopUpMenuApp theApp = new MyPopUpMenuApp();theApp.enterEventDispatcher();}Development Guide Pop-up menus145
  • public MyPopUpMenuApp(){pushScreen(new MyPopUpMenuScreen());}}class MyPopUpMenuScreen extends MainScreen{EmailAddressEditField emailAddress;public MyPopUpMenuScreen(){setTitle("Pop-Up Menu Demo");setContextMenuProvider(new DefaultContextMenuProvider());LabelField labelField = new LabelField("Click to invoke pop-up menu",Field.FOCUSABLE);emailAddress = new EmailAddressEditField("Email address: ","name@blackberry.com", 40);ItemProvider itemProvider = new ItemProvider();labelField.setCommandItemProvider(itemProvider);emailAddress.setCommandItemProvider(itemProvider);add(labelField);add(emailAddress);}/* To override the default functionality that prompts the user to save changesbefore the application closes,* override the MainScreen.onSavePrompt() method. In the following code sample,the return value is true which* indicates that the application does not prompt the user before closing.*/protected boolean onSavePrompt(){return true;}class ItemProvider implements CommandItemProvider{public Object getContext(Field field){return field;}public Vector getItems(Field field){Vector items = new Vector();CommandItem defaultCmd;Image myIcon = ImageFactory.createImage(BitmapDevelopment Guide Pop-up menus146
  • .getBitmapResource("my_logo.png"));if(field.equals(emailAddress)){defaultCmd = new CommandItem(new StringProvider("Email Address"),myIcon, new Command(new DialogCommandHandler()));}else{defaultCmd = new CommandItem(new StringProvider("Label Field"),myIcon, new Command(new DialogCommandHandler()));}items.addElement(defaultCmd);return items;}}class DialogCommandHandler extends CommandHandler{public void execute(ReadOnlyCommandMetadata metadata, Object context){Dialog.alert("Executing command for " + context.toString());}}}Adding a menu item to a BlackBerry Device Software applicationYou can add a menu item to a BlackBerry® Device Software application by using the Menu Item API in thenet.rim.blackberry.api.menuitem package. For example, you can add a menu item called View Sales Order to thecontacts application on a BlackBerry device so that when a user clicks the menu item, a CRM application opens and displays alist of sales orders for that contact.The ApplicationMenuItemRepository class provides the constants that specify the BlackBerry Device Softwareapplication that your menu item should appear in. For example, the MENUITEM_MESSAGE_LIST constant specifies that themenu item should appear in the messages application.Add a menu item to a BlackBerry Device Software application1. Import the required classes and interfaces.import net.rim.blackberry.api.menuitem.*;import net.rim.blackberry.api.pdap.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;Development Guide Adding a menu item to a BlackBerry Device Software application147
  • 2. Extend the abstract ApplicationMenuItem class to create a menu item. Override the ApplicationMenuItem()constructor with an integer to specify the position of the menu item in the menu. A higher number positions the menu itemlower in the menu.public class SampleMenuItem extends ApplicationMenuItem{SampleMenuItem(){super(20);}}3. Implement toString() to specify the menu item text.public String toString(){return "Open the Contacts Demo application";}4. Invoke getInstance() to retrieve the application repository.ApplicationMenuItemRepository repository =ApplicationMenuItemRepository.getInstance();5. Create an instance of a class to extend the MenuItem class.ContactsDemoMenuItem contactsDemoMenuItem = newContactsDemoMenuItem();6. Invoke ApplicationMenuItemRepository.addMenuItem() to add the menu item to the relevant BlackBerry®device application repository.repository.addMenuItem(ApplicationMenuItemRepository.MENUITEM_ADDRESSCARD_VIEW, contactsDemoMenuItem);7. Implement run() to specify the behavior of the menu item. In the following code sample, when a user clicks the new menuitem and a Contact object exists, the ContactsDemo application receives the event and invokesContactsDemo.enterEventDispatcher().public Object run(Object context){BlackBerryContact c = (BlackBerryContact)context;if ( c != null ){new ContactsDemo().enterEventDispatcher();}else{throw new IllegalStateException( "Context is null, expected a Contactinstance");}Development Guide Adding a menu item to a BlackBerry Device Software application148
  • Dialog.alert("Viewing an email message in the email view");return null;}Changing the appearance of a menuYou can change the background, border, and font of a menu by using the Menu class in thenet.rim.device.api.ui.component package. For example, you can change the appearance of the menu so that it hasa look and feel that is similar to the rest of your BlackBerry® device application. When you change the appearance of a menu,your BlackBerry device application overrides the theme that is set on the BlackBerry device.Change the appearance of a menu1. Import the required classes and interfaces.import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;import net.rim.device.api.ui.decor.*;import net.rim.device.api.system.*;2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor,invoke pushScreen() to display the custom screen for the application. The CreateCustomMenuScreen class , whichis described in step 3, represents the custom screen.public class CreateCustomMenu extends UiApplication{public static void main(String[] args){CreateCustomMenu theApp = new CreateCustomMenu();theApp.enterEventDispatcher();}public CreateCustomMenu(){pushScreen(new CreateCustomMenuScreen());}}3. Create the custom screen for the application by extending the MainScreen class. In the screen constructor, invokesetTitle() to specify the title for the screen. Invoke add() to add a text field on the screen.class CreateCustomMenuScreen extends MainScreen{Background _menuBackground;Border _menuBorder;Font _menuFont;CreateCustomMenuScreen()Development Guide Changing the appearance of a menu149
  • {setTitle("Custom Menu Sample");add(new RichTextField("Creating a custom menu"));}}4. In the screen constructor, specify the appearance of the menu. Create the spacing for the border around the menu bycreating an XYEdges object. Invoke createRoundedBorder() to create a border with rounded corners. InvokecreateSolidTransparentBackground() to create a transparent background color for the menu.XYEdges thickPadding = new XYEdges(10, 10, 10, 10);_menuBorder = BorderFactory.createRoundedBorder(thickPadding,Border.STYLE_DOTTED);_menuBackground = BackgroundFactory.createSolidTransparentBackground(Color.LIGHTSTEELBLUE, 50);5. In the screen constructor, specify the font for the menu by using a FontFamily object. Invoke forName() to retrieve afont from on the BlackBerry® device. Invoke getFont() to specify the style and size of the font.try{FontFamily family = FontFamily.forName("BBCasual");_menuFont = family.getFont(Font.PLAIN, 30, Ui.UNITS_px);}catch(final ClassNotFoundException cnfe){UiApplication.getUiApplication().invokeLater(new Runnable(){public void run(){Dialog.alert("FontFamily.forName() threw " + cnfe.toString());}});}6. Inthescreenclass,overridemakeMenu()toapplytheappearanceofthemenu.InvokesetBackground(),setBorder(), and setFont() to apply the appearance the menu that you specified in steps 4 and 5.protected void makeMenu(Menu menu, int context){menu.setBorder(_menuBorder);menu.setBackground(_menuBackground);menu.setFont(_menuFont);super.makeMenu(menu, context);}Code sample: Changing the appearance of a menuimport net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;Development Guide Changing the appearance of a menu150
  • import net.rim.device.api.ui.decor.*;import net.rim.device.api.system.*;public class CreateCustomMenu extends UiApplication{public static void main(String[] args){CreateCustomMenu theApp = new CreateCustomMenu();theApp.enterEventDispatcher();}public CreateCustomMenu(){pushScreen(new CreateCustomMenuScreen());}}class CreateCustomMenuScreen extends MainScreen{Border _menuBorder;Background _menuBackground;Font _menuFont;CreateCustomMenuScreen(){setTitle("Custom Menu Sample");add(new RichTextField("Creating a custom menu"));XYEdges thickPadding = new XYEdges(10, 10, 10, 10);_menuBorder = BorderFactory.createRoundedBorder(thickPadding,Border.STYLE_DOTTED);_menuBackground = BackgroundFactory.createSolidTransparentBackground(Color.LIGHTSTEELBLUE, 50);try{FontFamily family = FontFamily.forName("BBCasual");_menuFont = family.getFont(Font.PLAIN, 30, Ui.UNITS_px);}catch(final ClassNotFoundException cnfe){UiApplication.getUiApplication().invokeLater(new Runnable(){public void run(){Dialog.alert("FontFamily.forName() threw " + cnfe.toString());}});}}protected void makeMenu(Menu menu, int context){menu.setBorder(_menuBorder);menu.setBackground(_menuBackground);menu.setFont(_menuFont);Development Guide Changing the appearance of a menu151
  • super.makeMenu(menu, context);}}Development Guide Changing the appearance of a menu152
  • Custom fonts 11The FontManager class in the net.rim.device.api.ui package provides constants and methods that you can use toinstall and uninstall a TrueType font on a BlackBerry® device. The maximum size allowed for the TrueType font file is 60 KB. Youcan specify whether the font is available to the application that installs the font or to all applications on the BlackBerry device.The FontManager class also provides methods to set the default font for the BlackBerry device or application.Install and use a custom font in a BlackBerry Java application1. Import the required classes and interfaces.import net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;import net.rim.device.api.ui.component.*;import java.util.*;2. Create the application framework by extending the UiApplication class. In main(), create an instance of the newclass and invoke enterEventDispatcher() to enable the application to receive events. In the application constructor,invoke pushScreen() to display the custom screen for the application. The FontLoadingDemoScreen class,described in step 3, represents the custom screen.public class FontLoadingDemo extends UiApplication{public static void main(String[] args){FontLoadingDemo app = new FontLoadingDemo();app.enterEventDispatcher();}public FontLoadingDemo(){pushScreen(new FontLoadingDemoScreen());}}3. Create the custom screen by extending the MainScreen class. Invoke setTitle() to set the text that appears in thetitle section of the screen. Create a new LabelField object. You will apply the custom font to this object.class FontLoadingDemoScreen extends MainScreen{public FontLoadingDemoScreen(){setTitle("Font Loading Demo");LabelField helloWorld = new LabelField("Hello World");Development Guide Custom fonts153
  • }}4. In the screen constructor, invoke the FontManager.getInstance() method to get a reference to theFontManager object, then invoke the load() method to install the font. Wrap the load() invocation in an IF statementto check if the installation was successful. The load() method returns a flag specifying if font is successfully installed.The following code specifies that the font that can be used only by the application.if (FontManager.getInstance().load("Myfont.ttf", "MyFont",FontManager.APPLICATION_FONT) == FontManager.SUCCESS){}5. In the screen constructor, in a try/catch block in the IF statement you created in step 5, create a Font object for the fontyou just installed. Invoke the setFont() method to apply the font to the LabelField you created in step 5.try{FontFamily family = FontFamily.forName("MyFont");Font myFont = family.getFont(Font.PLAIN, 50);helloWorld.setFont(myFont);}catch (ClassNotFoundException e){System.out.println(e.getMessage());}6. In the screen constructor, invoke add() to add the LabelField to the screen.add(helloWorld);Code sample: Installing and using a custom font in a BlackBerry Javaapplicationimport net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.container.*;import net.rim.device.api.ui.component.*;import java.util.*;public class FontLoadingDemo extends UiApplication{public static void main(String[] args){FontLoadingDemo app = new FontLoadingDemo();app.enterEventDispatcher();}Development Guide Code sample: Installing and using a custom font in a BlackBerry Java application154
  • public FontLoadingDemo(){pushScreen(new FontLoadingDemoScreen());}}class FontLoadingDemoScreen extends MainScreen{public FontLoadingDemoScreen(){setTitle("Font Loading Demo");LabelField helloWorld = new LabelField("Hello World");if (FontManager.getInstance().load("Myfont.ttf", "MyFont",FontManager.APPLICATION_FONT) == FontManager.SUCCESS){try{FontFamily typeface = FontFamily.forName("MyFont");Font myFont = typeface.getFont(Font.PLAIN, 50);helloWorld.setFont(myFont);}catch (ClassNotFoundException e){System.out.println(e.getMessage());}}add(helloWorld);}}Development Guide Code sample: Installing and using a custom font in a BlackBerry Java application155
  • Spelling checker 12You can use the items in the net.rim.blackberry.api.spellcheck package to add spelling checker functionality toan application. The SpellCheckEngine interface enables an application to check the spelling of a UI field value and providea BlackBerry® device user with options for spelling corrections. The SpellCheckUI interface enables an application to providea UI that allows a BlackBerry device user to resolve a spelling issue- by interacting with the SpellCheckEngineimplementation.FormoreinformationaboutusingtheSpellCheckAPI,seetheSpellChecksampleapplication,whichisprovidedwithBlackBerry®Java® Development Environment 4.3.1 or later, and with the BlackBerry® Java® Plug-in for Eclipse®.Add spell check functionality1. Import the following classes:• net.rim.blackberry.api.spellcheck.SpellCheckEngineFactory• java.lang.StringBuffer2. Import the following interfaces:• net.rim.blackberry.api.spellcheck.SpellCheckEngine• net.rim.blackberry.api.spellcheck.SpellCheckUI• net.rim.blackberry.api.spellcheck.SpellCheckUIListener3. Create variables for spell check objects.SpellCheckEngine _spellCheckEngine;SpellCheckUI _spellCheckUI;4. Invoke createSpellCheckUI()._spellCheckUI = SpellCheckEngineFactory.createSpellCheckUI();5. To notifiy an application when a spell check event occurs, invoke addSpellCheckUIListener() with aSpellCheckUIListener object as a parameter._spellCheckUI.addSpellCheckUIListener(new SpellCheckUIListener());6. To let an application spell check UI fields and suggest spelling corrections to a BlackBerry device user, obtain aSpellCheckEngine object, invoke getSpellCheckEngine()._spellCheckEngine = _spellCheckUI.getSpellCheckEngine();7. To use a correction for a misspelled word, invoke SpellCheckEngine.learnCorrection(). Use the parametersnewStringBuffer(text), newStringBuffer(correction), where text represents the misspelled word, andcorrection represents the correct word.Development Guide Spelling checker156
  • _spellCheckEngine.learnCorrection(new StringBuffer(text), new StringBuffer(correction));8. To perform spell check operations on a field, invoke SpellCheckUI.spellCheck(), with a field as a parameter._spellCheckUI.spellCheck(field);9. To accept a misspelled word as correctly spelled, invoke SpellCheckEngine.learnWord(), with the word to learnas a parameter._spellCheckEngine.learnWord(new StringBuffer(word));Listen for a spell check event1. Import the following classes:• java.lang.StringBuffer• net.rim.device.api.ui.UiApplication• net.rim.device.api.ui.Field2. Import the following interfaces:• net.rim.blackberry.api.spellcheck.SpellCheckUIListener• net.rim.blackberry.api.spellcheck.SpellCheckEngine3. Create a method that returns the SpellCheckUIListener.LEARNING_ACCEPT constant when theSpellCheckEngine learns a new word.public int wordLearned(SpellCheckUI ui, StringBuffer word) {UiApplication.getUiApplication().invokeLater(new popUpRunner("Word learned"));return SpellCheckUIListener.LEARNING_ACCEPT;}4. Create a method that returns the SpellCheckUIListener.LEARNING_ACCEPT constant when theSpellCheckEngine learns a correction for a word.public int wordCorrectionLearned(SpellCheckUI ui, StringBuffer word, StringBuffercorrection){UiApplication.getUiApplication().invokeLater(new popUpRunner("Correctionlearned"));return SpellCheckUIListener.LEARNING_ACCEPT;}5. Create a method that returns the SpellCheckUIListener.ACTION_OPEN_UI constant when theSpellCheckEngine finds a misspelled word.public int misspelledWordFound(SpellCheckUI ui, Field field, int offset, int len){UiApplication.getUiApplication().invokeLater(new popUpRunner("Misspelled wordfound"));return SpellCheckUIListener.ACTION_OPEN_UI;}Development Guide Listen for a spell check event157
  • Related resources 13• www.blackberry.com/go/apiref: View the latest version of the API reference for the BlackBerry® Java® SDK.• www.blackberry.com/go/devguides: Find development guides, release notes, and sample application overviews for theBlackBerry Java SDK.• www.blackberry.com/developers: Visit the BlackBerry® Developer Zone for resources on developing BlackBerry deviceapplications.• www.blackberry.com/go/developerkb: View knowledge base articles on the BlackBerry Development Knowledge Base.• www.blackberry.com/developers/downloads: Find the latest development tools and downloads for developing BlackBerrydevice applications.Development Guide Related resources158
  • Glossary 143-Dthree-dimensionalAPIapplication programming interfaceJVMJava® Virtual MachineMIDPMobile Information Device ProfileDevelopment Guide Glossary159
  • Provide feedback 15To provide feedback on this deliverable, visit www.blackberry.com/docsfeedback.Development Guide Provide feedback160
  • Document revision history 16Date Description16 August 2010 Removed the following topic:• Create a progress indicator3 August 2010 Added the following topics:• Access an encoded image through an input stream• About placing items in the pop-up menus• Best practice: Implementing pop-up menus• Best practice: Implementing submenus• Command Framework API• Creating a pop-up menu• Create a pop-up menu• Create a submenu• Display a label at an absolute position on the screen• Display an encoded image• Display an image for zooming and panning• Display a row of images for scrolling• Displaying a field at an absolute position on a screen• Displaying an image for zooming and panning• Displaying a row of images for scrolling• Enable pinch gestures• Enable swipe gestures that users make on the trackpad• Encode an image• Images• Indicate activity• Indicate progress• Indicating activity or task progress• Pinch gestures• Pop-up menus• Specify the decoding mode for an imageDevelopment Guide Document revision history161
  • Date Description• Specify the display size of an encoded image• Submenus• Support for legacy context menus• Swipe gestures with trackpads• Touch screen interaction models• Use a command in one or more applications• Use a command with one UI component• Using encoded imagesAdded the following code samples:• Code sample: Creating a pop-up menu• Code sample: Creating a submenu• Code sample: Displaying a row of images for scrolling• Code sample: Displaying a label at an absolute position on the screen• Code sample: Displaying an image for zooming and panningChanged the following topics:• Activity indicators and progress indicators• Buttons• Creating a UI that is consistent with standard BlackBerry UIs• Dialog boxes• Drop-down lists• Lists and tables• Pickers• Radio buttons• Search• Spin boxes• Text fields• Tree viewsRemoved the following topics:• Adding an icon to a menu itemDevelopment Guide Document revision history162
  • Date Description• Add an icon to a menu item• Code sample: Adding an icon to a menu itemDevelopment Guide Document revision history163
  • Legal notice 17©2010 Research In Motion Limited. All rights reserved. BlackBerry®, RIM®, Research In Motion®, and related trademarks, names,and logos are the property of Research In Motion Limited and are registered and/or used in the U.S. and countries around theworld.Eclipse is a trademark of Eclipse Foundation, Inc. Java is a trademark of Oracle America, Inc. TrueType is a trademark of AppleInc. All other trademarks are the property of their respective owners.This documentation including all documentation incorporated by reference herein such as documentation provided or madeavailable at www.blackberry.com/go/docs is provided or made accessible "AS IS" and "AS AVAILABLE" and without condition,endorsement, guarantee, representation, or warranty of any kind by Research In Motion Limited and its affiliated companies("RIM") and RIM assumes no responsibility for any typographical, technical, or other inaccuracies, errors, or omissions in thisdocumentation. In order to protect RIM proprietary and confidential information and/or trade secrets, this documentation maydescribe some aspects of RIM technology in generalized terms. RIM reserves the right to periodically change information thatis contained in this documentation; however, RIM makes no commitment to provide any such changes, updates, enhancements,or other additions to this documentation to you in a timely manner or at all.This documentation might contain references to third-party sources of information, hardware or software, products or servicesincluding components and content such as content protected by copyright and/or third-party web sites (collectively the "ThirdParty Products and Services"). RIM does not control, and is not responsible for, any Third Party Products and Services including,without limitation the content, accuracy, copyright compliance, compatibility, performance, trustworthiness, legality, decency,links, or any other aspect of Third Party Products and Services. The inclusion of a reference to Third Party Products and Servicesin this documentation does not imply endorsement by RIM of the Third Party Products and Services or the third party in any way.EXCEPT TO THE EXTENT SPECIFICALLY PROHIBITED BY APPLICABLE LAW IN YOUR JURISDICTION, ALL CONDITIONS,ENDORSEMENTS, GUARANTEES, REPRESENTATIONS, OR WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDINGWITHOUT LIMITATION, ANY CONDITIONS, ENDORSEMENTS, GUARANTEES, REPRESENTATIONS OR WARRANTIES OFDURABILITY, FITNESS FOR A PARTICULAR PURPOSE OR USE, MERCHANTABILITY, MERCHANTABLE QUALITY, NON-INFRINGEMENT,SATISFACTORYQUALITY,ORTITLE,ORARISINGFROMASTATUTEORCUSTOMORACOURSEOFDEALINGOR USAGE OF TRADE, OR RELATED TO THE DOCUMENTATION OR ITS USE, OR PERFORMANCE OR NON-PERFORMANCEOF ANY SOFTWARE, HARDWARE, SERVICE, OR ANY THIRD PARTY PRODUCTS AND SERVICES REFERENCED HEREIN, AREHEREBY EXCLUDED. YOU MAY ALSO HAVE OTHER RIGHTS THAT VARY BY STATE OR PROVINCE. SOME JURISDICTIONSMAY NOT ALLOW THE EXCLUSION OR LIMITATION OF IMPLIED WARRANTIES AND CONDITIONS. TO THE EXTENTPERMITTED BY LAW, ANY IMPLIED WARRANTIES OR CONDITIONS RELATING TO THE DOCUMENTATION TO THE EXTENTTHEY CANNOT BE EXCLUDED AS SET OUT ABOVE, BUT CAN BE LIMITED, ARE HEREBY LIMITED TO NINETY (90) DAYS FROMTHE DATE YOU FIRST ACQUIRED THE DOCUMENTATION OR THE ITEM THAT IS THE SUBJECT OF THE CLAIM.TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW IN YOUR JURISDICTION, IN NO EVENT SHALL RIM BE LIABLEFOR ANY TYPE OF DAMAGES RELATED TO THIS DOCUMENTATION OR ITS USE, OR PERFORMANCE OR NON-PERFORMANCE OF ANY SOFTWARE, HARDWARE, SERVICE, OR ANY THIRD PARTY PRODUCTS AND SERVICES REFERENCEDHEREIN INCLUDING WITHOUT LIMITATION ANY OF THE FOLLOWING DAMAGES: DIRECT, CONSEQUENTIAL, EXEMPLARY,INCIDENTAL,INDIRECT,SPECIAL,PUNITIVE,ORAGGRAVATEDDAMAGES,DAMAGESFORLOSSOFPROFITSORREVENUES,FAILURE TO REALIZE ANY EXPECTED SAVINGS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, LOSS OFDevelopment Guide Legal notice164
  • BUSINESSOPPORTUNITY,ORCORRUPTIONORLOSSOFDATA,FAILURESTOTRANSMITORRECEIVEANYDATA,PROBLEMSASSOCIATED WITH ANY APPLICATIONS USED IN CONJUNCTION WITH RIM PRODUCTS OR SERVICES, DOWNTIME COSTS,LOSS OF THE USE OF RIM PRODUCTS OR SERVICES OR ANY PORTION THEREOF OR OF ANY AIRTIME SERVICES, COST OFSUBSTITUTE GOODS, COSTS OF COVER, FACILITIES OR SERVICES, COST OF CAPITAL, OR OTHER SIMILAR PECUNIARYLOSSES, WHETHER OR NOT SUCH DAMAGES WERE FORESEEN OR UNFORESEEN, AND EVEN IF RIM HAS BEEN ADVISEDOF THE POSSIBILITY OF SUCH DAMAGES.TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW IN YOUR JURISDICTION, RIM SHALL HAVE NO OTHEROBLIGATION, DUTY, OR LIABILITY WHATSOEVER IN CONTRACT, TORT, OR OTHERWISE TO YOU INCLUDING ANY LIABILITYFOR NEGLIGENCE OR STRICT LIABILITY.THE LIMITATIONS, EXCLUSIONS, AND DISCLAIMERS HEREIN SHALL APPLY: (A) IRRESPECTIVE OF THE NATURE OF THECAUSEOFACTION,DEMAND,ORACTIONBYYOUINCLUDINGBUTNOTLIMITEDTOBREACHOFCONTRACT,NEGLIGENCE,TORT, STRICT LIABILITY OR ANY OTHER LEGAL THEORY AND SHALL SURVIVE A FUNDAMENTAL BREACH OR BREACHESOR THE FAILURE OF THE ESSENTIAL PURPOSE OF THIS AGREEMENT OR OF ANY REMEDY CONTAINED HEREIN; AND (B)TO RIM AND ITS AFFILIATED COMPANIES, THEIR SUCCESSORS, ASSIGNS, AGENTS, SUPPLIERS (INCLUDING AIRTIMESERVICE PROVIDERS), AUTHORIZED RIM DISTRIBUTORS (ALSO INCLUDING AIRTIME SERVICE PROVIDERS) AND THEIRRESPECTIVE DIRECTORS, EMPLOYEES, AND INDEPENDENT CONTRACTORS.IN ADDITION TO THE LIMITATIONS AND EXCLUSIONS SET OUT ABOVE, IN NO EVENT SHALL ANY DIRECTOR, EMPLOYEE,AGENT, DISTRIBUTOR, SUPPLIER, INDEPENDENT CONTRACTOR OF RIM OR ANY AFFILIATES OF RIM HAVE ANY LIABILITYARISING FROM OR RELATED TO THE DOCUMENTATION.Prior to subscribing for, installing, or using any Third Party Products and Services, it is your responsibility to ensure that yourairtimeserviceproviderhasagreedtosupportalloftheirfeatures.SomeairtimeserviceprovidersmightnotofferInternetbrowsingfunctionality with a subscription to the BlackBerry® Internet Service. Check with your service provider for availability, roamingarrangements,serviceplansandfeatures.InstallationoruseofThirdPartyProductsandServiceswithRIMsproductsandservicesmay require one or more patent, trademark, copyright, or other licenses in order to avoid infringement or violation of third partyrights. You are solely responsible for determining whether to use Third Party Products and Services and if any third party licensesare required to do so. If required you are responsible for acquiring them. You should not install or use Third Party Products andServices until all necessary licenses have been acquired. Any Third Party Products and Services that are provided with RIMsproducts and services are provided as a convenience to you and are provided "AS IS" with no express or implied conditions,endorsements, guarantees, representations, or warranties of any kind by RIM and RIM assumes no liability whatsoever, in relationthereto. Your use of Third Party Products and Services shall be governed by and subject to you agreeing to the terms of separatelicenses and other agreements applicable thereto with third parties, except to the extent expressly covered by a license or otheragreement with RIM.CertainfeaturesoutlinedinthisdocumentationrequireaminimumversionofBlackBerry®EnterpriseServer,BlackBerry®DesktopSoftware, and/or BlackBerry® Device Software.The terms of use of any RIM product or service are set out in a separate license or other agreement with RIM applicable thereto.NOTHINGINTHISDOCUMENTATIONISINTENDEDTOSUPERSEDEANYEXPRESSWRITTENAGREEMENTSORWARRANTIESPROVIDED BY RIM FOR PORTIONS OF ANY RIM PRODUCT OR SERVICE OTHER THAN THIS DOCUMENTATION.Research In Motion Limited295 Phillip StreetDevelopment Guide Legal notice165
  • Waterloo, ON N2L 3W8CanadaResearch In Motion UK LimitedCentrum House36 Station RoadEgham, Surrey TW20 9LFUnited KingdomPublished in CanadaDevelopment Guide Legal notice166