The following code will display splash screen.
public class App extends UiApplication {
public static App theApp;
public static void main(String[] args) {
theApp = new App();
theApp.enterEventDispatcher();
}
public App() {
splash next = null;
splash1 splash1=new splash1(this ,next);
pushScreen(splash1);
}
}
splash1 class is given below-
public splash1(UiApplication app, splash next){
application=app;
VerticalFieldManager vfm=new VerticalFieldManager();
final Bitmap header_Bitmap =Bitmap.getBitmapResource("splash.png");
BitmapField bit =new BitmapField(header_Bitmap);
vfm.add(bit);
add(vfm);
timer = new Timer();
timer.schedule(new CountDown(), 1000);
}
public class CountDown extends TimerTask {
public void run() {
DismissThread dThread = new DismissThread();
application.invokeLater(dThread);
}
}
public void dismiss() {
timer.cancel();
application.popScreen(this);
application.pushScreen(next);
}
public class DismissThread implements Runnable {
public void run() {
dismiss();
}
}
}
splash class is the landing page(Home page)-
public class splash extends MainScreen {
public splash(){
//Here you can add your fields.......
}
}
Friday, September 20, 2013
Splash / Loading Screen in Blackberry
Thursday, September 5, 2013
Creating Facebook Like Slider Menu in Blackberry
For creating a sliding bar like android facebook app, refer the following code. You have to customize it. Its only give you the idea. you have to implement it in your own way.
public final class MyScreen extends MainScreen
{
boolean val=false;
VerticalFieldManager vfm_r1;
public MyScreen()
{
final ButtonField l=new ButtonField("menu");
final HorizontalFieldManager hfm_main=new HorizontalFieldManager();
final VerticalFieldManager vfm_l=new VerticalFieldManager(){
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout(280, maxHeight);
setExtent(280, maxHeight);
}
protected void paint(Graphics g){
g.setBackgroundColor(Color.RED);
// Clears the entire graphic area to the current background
g.clear();
super.paint(g);
}
};
final VerticalFieldManager vfm_r=new VerticalFieldManager(){
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout(maxWidth+300, maxHeight);
setExtent(maxWidth, maxHeight);
}
protected void paint(Graphics g){
g.setBackgroundColor(Color.YELLOW);
// Clears the entire graphic area to the current background
g.clear();
super.paint(g);
}
};
vfm_l.add(new LabelField("sliding pannel"));
vfm_r.add(l);
vfm_r.add(new LabelField("main view"));
hfm_main.add(vfm_r);
add(hfm_main);
FieldChangeListener listener=new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if(field==l){
if(!val){
val=true;
hfm_main.deleteAll();
hfm_main.add(vfm_l);
hfm_main.add(vfm_r);
hfm_main.invalidate();
}else{
val=false;
hfm_main.deleteAll();
hfm_main.add(vfm_r);
hfm_main.invalidate();
}
}
}
};
l.setChangeListener(listener);
}
}
public final class MyScreen extends MainScreen
{
boolean val=false;
VerticalFieldManager vfm_r1;
public MyScreen()
{
final ButtonField l=new ButtonField("menu");
final HorizontalFieldManager hfm_main=new HorizontalFieldManager();
final VerticalFieldManager vfm_l=new VerticalFieldManager(){
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout(280, maxHeight);
setExtent(280, maxHeight);
}
protected void paint(Graphics g){
g.setBackgroundColor(Color.RED);
// Clears the entire graphic area to the current background
g.clear();
super.paint(g);
}
};
final VerticalFieldManager vfm_r=new VerticalFieldManager(){
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout(maxWidth+300, maxHeight);
setExtent(maxWidth, maxHeight);
}
protected void paint(Graphics g){
g.setBackgroundColor(Color.YELLOW);
// Clears the entire graphic area to the current background
g.clear();
super.paint(g);
}
};
vfm_l.add(new LabelField("sliding pannel"));
vfm_r.add(l);
vfm_r.add(new LabelField("main view"));
hfm_main.add(vfm_r);
add(hfm_main);
FieldChangeListener listener=new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if(field==l){
if(!val){
val=true;
hfm_main.deleteAll();
hfm_main.add(vfm_l);
hfm_main.add(vfm_r);
hfm_main.invalidate();
}else{
val=false;
hfm_main.deleteAll();
hfm_main.add(vfm_r);
hfm_main.invalidate();
}
}
}
};
l.setChangeListener(listener);
}
}
Wednesday, July 24, 2013
Showing Google Maps in Blackberry
The following code will show your location in google map. No inbuilt Maps neede for this. Just fetch the location and pass it here.
StringBuffer html;
String initial = "\r\n" +
" \r\n" +
" \r\n" +
" \r\n" +
"Google Maps Multiple Markers \r\n" +
" \r\n" +
"
\r\n" + "\r\n" +
"
\r\n" +
"\r\n" +
" \r\n" +
"
\r\n" + "
";
html=new StringBuffer();
html.append(initial);
//add your location here
String point = "['"+""+"',"+lattitude+","+longitude+","+""+"],";
html.append(point);
//add your location here
centerPoint = " center: new google.maps.LatLng("+lattitude+","+longitude+"),";
html.append(second);
html.append(centerPoint);
html.append(finalpart);
//System.out.println("Plot is"+html.toString());
BrowserFieldConfig _bfConfig = new BrowserFieldConfig();
_bfConfig.setProperty(BrowserFieldConfig.NAVIGATION_MODE,BrowserFieldConfig.NAVIGATION_MODE_POINTER);
_bfConfig.setProperty( BrowserFieldConfig.JAVASCRIPT_ENABLED, Boolean.TRUE );
_bfConfig.setProperty(BrowserFieldConfig.USER_AGENT, "MyApplication 1.0");
BrowserField myBrowserField = new BrowserField(_bfConfig);
myBrowserField.displayContent(html.toString(), "");
HorizontalFieldManager horf=new HorizontalFieldManager(HORIZONTAL_SCROLL);
horf.add(myBrowserField);
add(horf);
StringBuffer html;
String initial = "\r\n" +
" \r\n" +
" \r\n" +
" \r\n" +
"
" \r\n" +
"
\r\n" + "\r\n" +
"
\r\n" +
"\r\n" +
" \r\n" +
"
\r\n" + "
";
html=new StringBuffer();
html.append(initial);
//add your location here
String point = "['"+""+"',"+lattitude+","+longitude+","+""+"],";
html.append(point);
//add your location here
centerPoint = " center: new google.maps.LatLng("+lattitude+","+longitude+"),";
html.append(second);
html.append(centerPoint);
html.append(finalpart);
//System.out.println("Plot is"+html.toString());
BrowserFieldConfig _bfConfig = new BrowserFieldConfig();
_bfConfig.setProperty(BrowserFieldConfig.NAVIGATION_MODE,BrowserFieldConfig.NAVIGATION_MODE_POINTER);
_bfConfig.setProperty( BrowserFieldConfig.JAVASCRIPT_ENABLED, Boolean.TRUE );
_bfConfig.setProperty(BrowserFieldConfig.USER_AGENT, "MyApplication 1.0");
BrowserField myBrowserField = new BrowserField(_bfConfig);
myBrowserField.displayContent(html.toString(), "");
HorizontalFieldManager horf=new HorizontalFieldManager(HORIZONTAL_SCROLL);
horf.add(myBrowserField);
add(horf);
Thursday, June 27, 2013
Creating a persistent store in Blackberry
To create a persistent store, you create at least one PersistentObject.
Each PersistentObject has a unique key of type long.
Creating Store -
Retrive datas from store -
Creating Store -
static PersistentObject store; static { store = PersistentStore.getPersistentObject( 0xa1a569278238dad2L ); }
Insert datas to store -
String[] userinfo = {username, password}; synchronized(store) { store.setContents(userinfo); store.commit(); }
Retrive datas from store -
synchronized(store) { String[] currentinfo = (String[])store.getContents(); if(currentinfo == null) { Dialog.alert(_resources.getString(APP_ERROR)); } else { currentusernamefield.setText(currentinfo[0]); currentpasswordfield.setText(currentinfo[1]); } }
Creating Folder on SD Card in Blackberry
The File Connection API is implemented in the
javax.microedition.io.file
package.
Internal Storage - FileConnection fc = (FileConnection)Connector.open("file:///Store")
External Storage - FileConnection fc = (FileConnection)Connector.open("file:///SDCard")
Internal Storage - FileConnection fc = (FileConnection)Connector.open("file:///Store")
External Storage - FileConnection fc = (FileConnection)Connector.open("file:///SDCard")
Creating a folder-
try { FileConnection fc = (FileConnection)Connector.open(
"file:///SDCard/myfolder/"); if (!fc.exists()) { fc.mkdir(); } fc.close(); } catch (IOException ioe) { System.out.println(ioe.getMessage() ); }
Creating a file -
try { FileConnection fc = (FileConnection)Connector.open(
"file:///store/home/user/newfile.txt"); if (!fc.exists()) { fc.create(); } fc.close(); } catch (IOException ioe) { System.out.println(ioe.getMessage() ); }
Writing text to a file -
try { FileConnection fc = (FileConnection)Connector.open(
"file:///store/home/user/newfile.txt");
if (!fc.exists()) { fc.create(); } OutputStream outStream = fc.openOutputStream(); outStream.write("test content".getBytes()); outStream.close(); fc.close(); } catch (IOException ioe) { System.out.println(ioe.getMessage() ); }
SQLite database in Blackberry
Creating a SQLite database-
try { URI myURI = URI.create("file:///SDCard/Databases/" + "MyDatabase.db"); d = DatabaseFactory.create(myURI); d.close(); } catch ( Exception e ) { System.out.println( e.getMessage() ); e.printStackTrace(); }
Creating Table -
try { URI myURI = URI.create("/SDCard/Databases/" + "MyDatabase.db"); d = DatabaseFactory.open(myURI); Statement st = d.createStatement( "CREATE TABLE 'MyTable' ( " + "'Name' TEXT, " + "'Number' INTEGER )" ); st.prepare(); st.execute(); st.close(); d.close(); } catch ( Exception e ) { System.out.println( e.getMessage() ); e.printStackTrace(); }
Insert Data -
try { URI myURI = URI.create("file:///SDCard/Databases/" + "MyDatabase.db"); d = DatabaseFactory.open(myURI); Statement st = d.createStatement("INSERT INTO MyTable(Name,Number) " + "VALUES ('abc',123)"); st.prepare(); st.execute(); st.close(); d.close(); } catch ( Exception e ) { System.out.println( e.getMessage() ); e.printStackTrace(); }
Retrive data -
try { URI myURI = URI.create("file:///SDCard/Databases/" + "MyDatabase.db"); d = DatabaseFactory.open(myURI); Statement st = d.createStatement("SELECT Name,Number FROM MyTable"); st.prepare(); net.rim.device.api.database.Cursor c = st.getCursor(); Row r; int i = 0; while(c.next()) { r = c.getRow(); i++; add(new RichTextField(i + ". Name = " + r.getString(0) + " , " + "Number= " + r.getInteger(1))); } if (i==0) { add(new RichTextField("No data in the MyTable table.")); } st.close(); d.close(); } catch ( Exception e ) { System.out.println( e.getMessage() ); e.printStackTrace(); }
Delete Table -
try { URI myURI = URI.create("file:///SDCard/Databases/" + "MyDatabase.db"); d = DatabaseFactory.open(myURI); Statement st = d.createStatement("DELETE MyTable"); st.prepare(); st.execute(); st.close(); d.close(); } catch ( Exception e ) { System.out.println( e.getMessage() ); e.printStackTrace(); }
Update Table -
try { URI myURI = URI.create("file:///SDCard/Databases/" + "MyDatabase.db"); d = DatabaseFactory.open(myURI); Statement st = d.createStatement("UPDATE MyTable SET Number=1" + "WHERE Name='abc'"); st.prepare(); st.execute(); st.close(); d.close(); } catch ( Exception e ) { System.out.println( e.getMessage() ); e.printStackTrace(); }
Delete Database -
try { URI myURI = URI.create("file:///SDCard/Databases/" + "MyDatabase.db"); DatabaseFactory.delete(myURI); } catch ( Exception e ) { System.out.println( e.getMessage() ); e.printStackTrace(); }
Storing data in Blackberry
There are several ways you can store, share, and
manage data for your apps:
Data storage approach | Description and API |
---|---|
SQLite database | Store data in relational databases with the Database API. |
File system | Store data in files and folders with the FileConnection API. |
Persistent store | Save objects across smartphone restarts with the PersistentStore API. |
Runtime store | Save objects nonpersistently, which is useful for sharing data between applications and creating system-wide singletons, with the RuntimeStore API. |
Record store | Store data in the MIDP Record Management System with the RMS API. |
Navigation events in Blackberry
You can use the Screen navigation methods to create a BlackBerry
device application.
If your existing BlackBerry device application
implements the TrackwheelListener interface, update your
BlackBerry device application
to use the Screen navigation methods.
navigationClick(int status, int time) navigationUnclick(int status, int time) navigationMovement(int dx, int dy, int status, int time)
Navagation Click -
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); }
Touch Event -
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"); return true; case TouchEvent.MOVE: Dialog.alert("A move action occurred"); return true; } return false; }
Respond to a user touching the screen twice quickly -
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; }
Pinch gestures -
Enabling Pinch event -
InputSettings ts = TouchscreenSettings.createEmptySet(); ts.set(TouchscreenSettings.DETECT_PINCH, 1); addInputSettings(ts);
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; }
Screens in Blackberry
The main component of a
BlackBerry device UI is the
Screen object.
Screen classes
Screen | You can use the Screen class to create a screen and use a layout manager to lay out the UI components on the screen. You can define a specific type of screen by using 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 can add UI components in a standard vertical layout. If you want to use another layout style, such as horizontal or diagonal, you can use the Screen class instead and add a layout manager to it. |
MainScreen PopupScreen |
You can use the
MainScreen class to create a screen with the
following standard UI components:
Screen providing features for building dialog and status screens |
UI components in Blackberry
The net.rim.device.api.ui package contains the fundamental classes that are used for all UI applications:
The net.rim.device.api.ui.container package contains classes that you can use to arrange UI components on a screen, such as:
CheckBox -
CheckboxField chk=new CheckboxField("First Check Box", true);
add(new RadioButtonField("Option 1",rbg,true));
add(new RadioButtonField("Option 2",rbg,false));
- Field: A rectangular area that can be drawn on the screen of a device.
- Manager: An area that contains other UI components and handles layout and scrolling behavior.
- Screen: A drawable area that is pushed on to and popped off of an application's display stack.
- ButtonField: A simple button.
- DateField: A field that contains date and time values.
- LabelField: A text label.
- TextField: An editable text field.
The net.rim.device.api.ui.container package contains classes that you can use to arrange UI components on a screen, such as:
- FlowFieldManager: A manager that arranges fields horizontally and then vertically.
- HorizontalFieldManager: A manager that arranges fields in a single horizontal row.
- VerticalFieldManager: A manager that arranges fields in a single vertical column.
ButtonField mySubmitButton = new ButtonField("Submit");
CheckBox -
CheckboxField chk=new CheckboxField("First Check Box", true);
CheckboxField chk=new CheckboxField("First Check Box", false);
DialogBox -
Dialog.alert("Specify the alert text that you want to display.")
LabelField -LabelField title = new LabelField("UI Component Sample", LabelField.ELLIPSIS);
RadioButton -RadioButtonGroup rbg = new RadioButtonGroup();
add(new RadioButtonField("Option 1",rbg,true));
add(new RadioButtonField("Option 2",rbg,false));
DateTimePicker -
DateTimePicker datePicker = DateTimePicker.getInstance(); datePicker.doModal(); Calendar cal = datePicker.getDateTime(); Date date = cal.getTime(); Dialog.alert("You selected " + date.toString());
FilePicker -
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); } }
Text Fields -
RichTextField rich = new RichTextField("RichTextField");
BasicEditField bf = new BasicEditField( "BasicEditField: ", "", 10, EditField.FILTER_UPPERCASE);
EditField edit = new EditField( "EditField: ", "", 10, EditField.FILTER_DEFAULT);
AutoTextEditField autoT = new AutoTextEditField( "AutoTextEditField: ", "");
PasswordEditField pwd = new PasswordEditField("PasswordEditField: ", "");
Toolbar in Blackberry
Use a toolbar to provide users with a quick and easy way to access frequent
actions for an application or screen. Each toolbar consists of a set of icons
that appears along the bottom of the screen.
if (ToolbarManager.isToolbarSupported()) { setTitle("Toolbar Demo"); ToolbarManager manager = new ToolbarManager(); setToolbar(manager); try { Bitmap myBitmap = Bitmap.getBitmapResource("myImg.jpg"); Image myImage = ImageFactory.createImage(myBitmap); /* * To create more buttons, Repeat the following lines * up until manager.add() */ ToolbarButtonField button1 = new ToolbarButtonField(myImage, new StringProvider("butn1")); button1.setCommandContext(new Object() { public String toString() { return "Button1"; } }); button1.setCommand(new Command(new CommandHandler() { public void execute(ReadOnlyCommandMetadata metadata, Object context) { Dialog.alert("Executing command for " + context.toString()); } })); manager.add(new ToolbarSpacer(0)); manager.add(button1); } catch (Exception e) { System.out.println(e.getMessage()); } } else { Dialog.alert("The Toolbar is not supported on this device."); }
Title bar in Blackberry
Use a title bar to provide
BlackBerry device
users with information at the top of your application. Most title bars contain
only a title, but title bars can display the following items:
- application icon, descriptive title, and time
- application notifications, such as a new message indicator
- wireless connection indicators, including the wireless coverage level, network coverage, GPS indicator, Bluetooth indicator, and Wi-Fi connection indicator
- battery power indicator
- active call indicator
StandardTitleBar myTitleBar = new StandardTitleBar()
.addIcon("my_logo.png") .addTitle("Title Bar") .addClock() .addNotifications() .addSignalIndicator();
myTitleBar.setPropertyValue(StandardTitleBar.PROPERTY_BATTERY_VISIBILITY, StandardTitleBar.BATTERY_VISIBLE_LOW_OR_CHARGING); setTitleBar(myTitleBar);
BitmapField in Blackberry
Use a bitmap field to display bitmap images that a
BlackBerry device user can
view.
Bitmap bitmapImage = Bitmap.getBitmapResource("your_image.jpg"); BitmapField bitmap_img= new BitmapField(bitmapImage); add(bitmap_img);
Map field in Blackberry
Use a map field to display a map in a BlackBerry device
application.
MapField map = new MapField(); MapAction action = map.getAction(); action.setCentreAndZoom(new MapPoint(43.46518, -80.52237), 3); add(map);
Rich List in Blackberry
Use a rich list to display a list of items that contain an optional
image on the left, a list of labels beside the image and an optional
description below the image and labels.
Manager mainManager = getMainManager(); RichList list = new RichList(mainManager, true, 2, 1); Bitmap bitmap1 = Bitmap.getBitmapResource("9500.png"); Bitmap bitmap2 = Bitmap.getBitmapResource("9000.png"); list.add(new Object[] {bitmap1, "Device 1","BlackBerry 9500", "Description of Device 1."}); list.add(new Object[] {bitmap2, "Device 2","BlackBerry 9000", "Description of Device 2."});
Simple list in Blackberry
Use a simple list to display a list of items as text.
Manager mainManager = getMainManager(); SimpleList listField = new SimpleList(mainManager); listField.add("Item 1"); listField.add("Item 2"); listField.add("Item 3");
Auto complete field in Blackberry
The auto complete field sample application demonstrates how to create and configure an AutoCompleteField UI component using a variety of data sources. An AutoCompleteField is a text
field that displays a list of values as the user types text in the
field. The list contains values that match the field or criteria that
you specify.The AutoCompleteField
matches what the user types in the field against an associated data source.
BasicFilteredList filterList = new BasicFilteredList();
String[] currencyList = {RUB,AFN,EUR,ALL,GBP,GGP,DZD,EUR,AOA,XCD,XCD,
ARS,AMD,AWG,SHP,AUD,EUR};
int uniqueID = 0;
filterList.addDataSet(uniqueID,currencyList,"currency",
BasicFilteredList.COMPARISON_IGNORE_CASE);
AutoCompleteField autoCompleteField = new AutoCompleteField(filterList);
add(autoCompleteField);
Monday, June 3, 2013
Popup Screen with Transparent Background
public class popup extends PopupScreen
{
popup()
{
super(new HorizontalFieldManager());
setBackground (BackgroundFactory.createSolidTransparentBackground (Color.WHITE, 0));
setBorder (BorderFactory.createRoundedBorder(new XYEdges(),Color.BLACK,2));
//Here you can add Fields to the popup Screen.
}
}
{
popup()
{
super(new HorizontalFieldManager());
setBackground (BackgroundFactory.createSolidTransparentBackground (Color.WHITE, 0));
setBorder (BorderFactory.createRoundedBorder(new XYEdges(),Color.BLACK,2));
//Here you can add Fields to the popup Screen.
}
}
Wednesday, April 17, 2013
Image Animation in Blackberry (using a series of images)
final Bitmap image000 = Bitmap.getBitmapResource("1.png");
final Bitmap image001 = Bitmap.getBitmapResource("2.png");
final Bitmap image002 = Bitmap.getBitmapResource("3.png");
final Bitmap image003 = Bitmap.getBitmapResource("4.png");
final Bitmap image004 =Bitmap.getBitmapResource("5.png");
final Bitmap image005 = Bitmap.getBitmapResource("6.png");
final Bitmap image006 = Bitmap.getBitmapResource("7.png");
final Bitmap image007 = Bitmap.getBitmapResource("8.png");
final Bitmap image008 = Bitmap.getBitmapResource("9.png");
final Bitmap image009 =Bitmap.getBitmapResource("10.png");
final Bitmap image010 = Bitmap.getBitmapResource("11.png");
final Bitmap image011 =Bitmap.getBitmapResource("12.png");
final BitmapField animationField = new BitmapField(image000);
int counter=0;
Timer animationTimer = new Timer();
TimerTask animationTask;
animationTask = new TimerTask() {
public void run() { if(counter == 0){
animationField.setBitmap(image000); }
if(counter == 1){ animationField.setBitmap(image001); }
if(counter == 2){ animationField.setBitmap(image002); }
if(counter == 3){ animationField.setBitmap(image003); }
if(counter == 4){ animationField.setBitmap(image004); }
if(counter == 5){ animationField.setBitmap(image005); }
if(counter == 6){ animationField.setBitmap(image006); }
if(counter == 7){ animationField.setBitmap(image007); }
if(counter == 8){ animationField.setBitmap(image008); }
if(counter == 9){ animationField.setBitmap(image009); }
if(counter == 10){ animationField.setBitmap(image010); }
if(counter == 11){ animationField.setBitmap(image011);
counter = -1; } counter++;
} };
animationTimer.scheduleAtFixedRate(animationTask, 0, 100);
add(animationField);
final Bitmap image001 = Bitmap.getBitmapResource("2.png");
final Bitmap image002 = Bitmap.getBitmapResource("3.png");
final Bitmap image003 = Bitmap.getBitmapResource("4.png");
final Bitmap image004 =Bitmap.getBitmapResource("5.png");
final Bitmap image005 = Bitmap.getBitmapResource("6.png");
final Bitmap image006 = Bitmap.getBitmapResource("7.png");
final Bitmap image007 = Bitmap.getBitmapResource("8.png");
final Bitmap image008 = Bitmap.getBitmapResource("9.png");
final Bitmap image009 =Bitmap.getBitmapResource("10.png");
final Bitmap image010 = Bitmap.getBitmapResource("11.png");
final Bitmap image011 =Bitmap.getBitmapResource("12.png");
final BitmapField animationField = new BitmapField(image000);
int counter=0;
Timer animationTimer = new Timer();
TimerTask animationTask;
animationTask = new TimerTask() {
public void run() { if(counter == 0){
animationField.setBitmap(image000); }
if(counter == 1){ animationField.setBitmap(image001); }
if(counter == 2){ animationField.setBitmap(image002); }
if(counter == 3){ animationField.setBitmap(image003); }
if(counter == 4){ animationField.setBitmap(image004); }
if(counter == 5){ animationField.setBitmap(image005); }
if(counter == 6){ animationField.setBitmap(image006); }
if(counter == 7){ animationField.setBitmap(image007); }
if(counter == 8){ animationField.setBitmap(image008); }
if(counter == 9){ animationField.setBitmap(image009); }
if(counter == 10){ animationField.setBitmap(image010); }
if(counter == 11){ animationField.setBitmap(image011);
counter = -1; } counter++;
} };
animationTimer.scheduleAtFixedRate(animationTask, 0, 100);
add(animationField);
Thursday, March 28, 2013
Application Permissions in Blackberry
BlackBerry Enterprise Server administrators can control the data and
APIs that BlackBerry Java Applications can access on BlackBerry devices,
and the external data sources and network connections that BlackBerry
Java Applications can access by using application control policies. For
example, administrators can use application control policies to prevent
users from installing an application on a BlackBerry device.
Application control policies enable administrators to perform the following actions:
You can determine whether an API is available for use on a BlackBerry device and request that the user change permissions, if necessary. In the following code sample, the application checks whether the application control settings permit access to location-based services. If the API is unavailable, the application prompts the user for permission to use this API.
Application control policies enable administrators to perform the following actions:
- prevent users from installing and running applications on BlackBerry devices
- limit internal connections (connections behind a firewall)
- limit external connections
- limit local connections (serial, infrared, and USB connections)
- limit access to the key store
- limit access to particular APIs
You can determine whether an API is available for use on a BlackBerry device and request that the user change permissions, if necessary. In the following code sample, the application checks whether the application control settings permit access to location-based services. If the API is unavailable, the application prompts the user for permission to use this API.
ApplicationPermissionsManager appPermMgr =
ApplicationPermissionsManager.getInstance();
// Query the Location permission
int locationPermission = appPermMgr.getPermission(
ApplicationPermissions.PERMISSION_LOCATION_DATA );
if( locationPermission != ApplicationPermissions.VALUE_ALLOW ) {
// Build the permission request
ApplicationPermissions requestedPermissions =
new ApplicationPermissions();
requestedPermissions.addPermission(
ApplicationPermissions.PERMISSION_LOCATION_DATA );
// Invoke the request, the system takes over
appPermMgr.invokePermissionsRequest( requestedPermissions );
}
Friday, March 22, 2013
TreeField With CheckBox in Blackberry
The following code will help you in creating a TreeField with checkBox.
In Main Screen Class Add the CBTreeField to thhe Screen.
CBTreeField tree = new CBTreeField("root", false);
add(tree);
int ch01 = tree.addChildNode(0, "child 0-1", true, null);
int ch02 = tree.addChildNode(0, "child 0-2", false, null);
int ch03 = tree.addChildNode(0, "child 0-3", false, null);
int ch011 = tree.addChildNode(ch01, "child 0-1-1", false, null);
int ch012 = tree.addChildNode(ch01, "child 0-1-2", true, null);
int ch031 = tree.addChildNode(ch03, "child 0-3-1", true, null);
The CBTreeField class is given below -
public class CBTreeField extends VerticalFieldManager implements TreeFieldCallback,
DrawStyle {
boolean[] mBooleanValues = new boolean[] {};
String[] mStringValues = new String[] {};
public boolean getNodeBooleanValue(int node) {
return mBooleanValues[node];
}
public void setNodeBooleanValue(int node, boolean value) {
mBooleanValues[node] = value;
}
TreeField mRootField = null;
public CBTreeField(String rootString, boolean rootBoolean) {
mRootField = new TreeField(this, TreeField.FOCUSABLE);
add(mRootField);
mStringValues = insertAt(mStringValues, 0, rootString);
mBooleanValues = insertAt(mBooleanValues, 0, rootBoolean);
}
public int addSiblingNode(int previousSibling, String stringValue,
boolean booleanValue, Object cookie) {
int index = mRootField.addSiblingNode(previousSibling, cookie);
mBooleanValues = insertAt(mBooleanValues, index, booleanValue);
mStringValues = insertAt(mStringValues, index, stringValue);
return index;
}
public int addChildNode(int parent, String stringValue,
boolean booleanValue, Object cookie) {
int index = mRootField.addChildNode(parent, cookie);
mBooleanValues = insertAt(mBooleanValues, index, booleanValue);
mStringValues = insertAt(mStringValues, index, stringValue);
return index;
}
static boolean[] insertAt(boolean[] inArray, int index, boolean value) {
int newLen = inArray.length + 1;
boolean[] outArray = new boolean[newLen];
for (int i = 0, j = 0; i < newLen; i++, j++) {
outArray[i] = (i != index) ? inArray[j] : value;
if (i == index)
j++;
}
return outArray;
}
static String[] insertAt(String[] inArray, int index, String value) {
int newLen = inArray.length + 1;
String[] outArray = new String[newLen];
for (int i = 0, j = 0; i < newLen; i++, j++) {
outArray[i] = (i != index) ? inArray[j] : value;
if (i == index)
j++;
}
return outArray;
}
public void drawTreeItem(TreeField treeField, Graphics g, int node, int y,
int width, int indent) {
String check = String
.valueOf(mBooleanValues[node] ?
Characters.BALLOT_BOX_WITH_CHECK : Characters.BALLOT_BOX);
g.drawText(check, indent, y, DrawStyle.LEFT);
g.drawText(mStringValues[node], indent + 20, y, DrawStyle.RIGHT
| ELLIPSIS);
}
protected void makeMenu(Menu menu, int instance) {
super.makeMenu(menu, instance);
menu.add(new MenuItem("Change value", 0, 0) {
public void run() {
int node = mRootField.getCurrentNode();
mBooleanValues[node] = !mBooleanValues[node];
invalidate();
}
});
}
}
In Main Screen Class Add the CBTreeField to thhe Screen.
CBTreeField tree = new CBTreeField("root", false);
add(tree);
int ch01 = tree.addChildNode(0, "child 0-1", true, null);
int ch02 = tree.addChildNode(0, "child 0-2", false, null);
int ch03 = tree.addChildNode(0, "child 0-3", false, null);
int ch011 = tree.addChildNode(ch01, "child 0-1-1", false, null);
int ch012 = tree.addChildNode(ch01, "child 0-1-2", true, null);
int ch031 = tree.addChildNode(ch03, "child 0-3-1", true, null);
The CBTreeField class is given below -
public class CBTreeField extends VerticalFieldManager implements TreeFieldCallback,
DrawStyle {
boolean[] mBooleanValues = new boolean[] {};
String[] mStringValues = new String[] {};
public boolean getNodeBooleanValue(int node) {
return mBooleanValues[node];
}
public void setNodeBooleanValue(int node, boolean value) {
mBooleanValues[node] = value;
}
TreeField mRootField = null;
public CBTreeField(String rootString, boolean rootBoolean) {
mRootField = new TreeField(this, TreeField.FOCUSABLE);
add(mRootField);
mStringValues = insertAt(mStringValues, 0, rootString);
mBooleanValues = insertAt(mBooleanValues, 0, rootBoolean);
}
public int addSiblingNode(int previousSibling, String stringValue,
boolean booleanValue, Object cookie) {
int index = mRootField.addSiblingNode(previousSibling, cookie);
mBooleanValues = insertAt(mBooleanValues, index, booleanValue);
mStringValues = insertAt(mStringValues, index, stringValue);
return index;
}
public int addChildNode(int parent, String stringValue,
boolean booleanValue, Object cookie) {
int index = mRootField.addChildNode(parent, cookie);
mBooleanValues = insertAt(mBooleanValues, index, booleanValue);
mStringValues = insertAt(mStringValues, index, stringValue);
return index;
}
static boolean[] insertAt(boolean[] inArray, int index, boolean value) {
int newLen = inArray.length + 1;
boolean[] outArray = new boolean[newLen];
for (int i = 0, j = 0; i < newLen; i++, j++) {
outArray[i] = (i != index) ? inArray[j] : value;
if (i == index)
j++;
}
return outArray;
}
static String[] insertAt(String[] inArray, int index, String value) {
int newLen = inArray.length + 1;
String[] outArray = new String[newLen];
for (int i = 0, j = 0; i < newLen; i++, j++) {
outArray[i] = (i != index) ? inArray[j] : value;
if (i == index)
j++;
}
return outArray;
}
public void drawTreeItem(TreeField treeField, Graphics g, int node, int y,
int width, int indent) {
String check = String
.valueOf(mBooleanValues[node] ?
Characters.BALLOT_BOX_WITH_CHECK : Characters.BALLOT_BOX);
g.drawText(check, indent, y, DrawStyle.LEFT);
g.drawText(mStringValues[node], indent + 20, y, DrawStyle.RIGHT
| ELLIPSIS);
}
protected void makeMenu(Menu menu, int instance) {
super.makeMenu(menu, instance);
menu.add(new MenuItem("Change value", 0, 0) {
public void run() {
int node = mRootField.getCurrentNode();
mBooleanValues[node] = !mBooleanValues[node];
invalidate();
}
});
}
}
Wednesday, March 6, 2013
BlackBerry Internet Service (BIS)
The BlackBerry Internet Service is designed to provide users with real-time delivery of email messages, mobile access to attachments, and convenient access to Internet content.
The BlackBerry Internet Service uses the security of the wireless network that it connects to. Email messages that are sent between the BlackBerry Internet Service and a BlackBerry device are not encrypted. When email messages are sent over the wireless network, they are subject to the existing or available network security model(s). However, email messages that are sent between the BlackBerry Internet Service and a messaging server can be encrypted using Secure Sockets Layer (SSL) encryption. SSL encryption can also be used by the BlackBerry® Browser and other applications on a BlackBerry device to help protect data when a user connects to the Internet (for example, while shopping and banking online).
The BlackBerry Internet Service uses the security of the wireless network that it connects to. Email messages that are sent between the BlackBerry Internet Service and a BlackBerry device are not encrypted. When email messages are sent over the wireless network, they are subject to the existing or available network security model(s). However, email messages that are sent between the BlackBerry Internet Service and a messaging server can be encrypted using Secure Sockets Layer (SSL) encryption. SSL encryption can also be used by the BlackBerry® Browser and other applications on a BlackBerry device to help protect data when a user connects to the Internet (for example, while shopping and banking online).
BlackBerry Enterprise Server (BES)
The BlackBerry Enterprise Server is designed to be a secure, centralized link between an organization's wireless network, communications software, applications, and BlackBerry devices. The BlackBerry Enterprise Server integrates with an organization's existing infrastructure, which can include messaging and collaboration software, calendar and contact information, wireless Internet and intranet access, and custom applications, to provide BlackBerry device users with mobile access to the organization's resources.
The BlackBerry Enterprise Server supports Advanced Encryption Standard (AES) and Triple Data Encryption Standard (Triple DES) encryption to help protect and maintain the integrity of wireless data that is transmitted between the BlackBerry Enterprise Server components and BlackBerry devices. Administrators can choose from more than 450 IT policy rules that they can configure to control the features of the BlackBerry devices that are used in the organization's environment.
The BlackBerry Enterprise Server supports several optional components and configurations to meet the organization's requirements. The BlackBerry Collaboration Service integrates with supported third-party instant messaging servers to permit users to access the organization's instant messaging system from their BlackBerry devices using a BlackBerry instant messaging client. The BlackBerry MDS Integration Service supports custom application development and distribution. Administrators can configure the BlackBerry Enterprise Server and the BlackBerry Enterprise Server components to support high availability to enhance the consistency and reliability of the organization's environment.
The BlackBerry Enterprise Server supports Advanced Encryption Standard (AES) and Triple Data Encryption Standard (Triple DES) encryption to help protect and maintain the integrity of wireless data that is transmitted between the BlackBerry Enterprise Server components and BlackBerry devices. Administrators can choose from more than 450 IT policy rules that they can configure to control the features of the BlackBerry devices that are used in the organization's environment.
The BlackBerry Enterprise Server supports several optional components and configurations to meet the organization's requirements. The BlackBerry Collaboration Service integrates with supported third-party instant messaging servers to permit users to access the organization's instant messaging system from their BlackBerry devices using a BlackBerry instant messaging client. The BlackBerry MDS Integration Service supports custom application development and distribution. Administrators can configure the BlackBerry Enterprise Server and the BlackBerry Enterprise Server components to support high availability to enhance the consistency and reliability of the organization's environment.
Blackberry Device characteristics
Programmatically Power OFF Blackberry Device
net.rim.device.api.system.Device.requestPowerOff(true);
Tuesday, March 5, 2013
Email Address Validation in Blackberry
If validateEmailID returns true, then the entered email address is valid.
public static boolean validateEmailID(String email) {
email = email.trim();
String reverse = new StringBuffer(email).reverse().toString();
if (email == null || email.length() == 0 || email.indexOf("@") == -1) {
return false;
}
int emailLength = email.length();
int atPosition = email.indexOf("@");
int atDot = reverse.indexOf(".");
String beforeAt = email.substring(0, atPosition);
String afterAt = email.substring(atPosition + 1, emailLength);
if (beforeAt.length() == 0 || afterAt.length() == 0) {
return false;
}
for (int i = 0; email.length() - 1 > i; i++) {
char i1 = email.charAt(i);
char i2 = email.charAt(i + 1);
if (i1 == '.' && i2 == '.') {
return false;
}
}
if (email.charAt(atPosition - 1) == '.' || email.charAt(0) == '.' || email.charAt(atPosition + 1) == '.' || afterAt.indexOf("@") != -1 || atDot < 2) {
return false;
}
return true;
}
public static boolean validateEmailID(String email) {
email = email.trim();
String reverse = new StringBuffer(email).reverse().toString();
if (email == null || email.length() == 0 || email.indexOf("@") == -1) {
return false;
}
int emailLength = email.length();
int atPosition = email.indexOf("@");
int atDot = reverse.indexOf(".");
String beforeAt = email.substring(0, atPosition);
String afterAt = email.substring(atPosition + 1, emailLength);
if (beforeAt.length() == 0 || afterAt.length() == 0) {
return false;
}
for (int i = 0; email.length() - 1 > i; i++) {
char i1 = email.charAt(i);
char i2 = email.charAt(i + 1);
if (i1 == '.' && i2 == '.') {
return false;
}
}
if (email.charAt(atPosition - 1) == '.' || email.charAt(0) == '.' || email.charAt(atPosition + 1) == '.' || afterAt.indexOf("@") != -1 || atDot < 2) {
return false;
}
return true;
}
Wednesday, February 27, 2013
Display Calendar in Blackberry
The following code will display Calendar in blackberry.
public class CalendarPopupScreen extends MainScreen {
private static SimpleDateFormat sdfWeekDay = new SimpleDateFormat("E");
private static SimpleDateFormat sdfMonth = new SimpleDateFormat("MMMM yyyy");
private static String SINGLE_BLANK = " ";
private static String FIELD_SIZE_STRING = " 30 ";
private int _selectedDay = -1;
private int _currentFocusDay;
private int _currentMonth;
private String _currentMonthString;
private int _currentYear;
private Calendar _cl = Calendar.getInstance();
private ButtonBorderedLabelField _prevMonthButton;
private LabelField _currentMonthField;
private ButtonBorderedLabelField _nextMonthButton;
private static int [] tableStyles = new int [] {
TableLayoutManager.FIXED_WIDTH,
TableLayoutManager.FIXED_WIDTH,
TableLayoutManager.FIXED_WIDTH,
TableLayoutManager.FIXED_WIDTH,
TableLayoutManager.FIXED_WIDTH,
TableLayoutManager.FIXED_WIDTH,
TableLayoutManager.FIXED_WIDTH
};
private int [] tableSizes = new int [7] ;
private TableLayoutManager _monthManager;
private Field _initialFocusField = null;
private Font _normalFont;
private Font _boldFont;
public CalendarPopupScreen() {
this(new Date());
}
public CalendarPopupScreen(long dateMilliSecs) {
this(new Date(dateMilliSecs));
}
public CalendarPopupScreen(Date selectedDate) {
_cl.setTime(selectedDate);
createScreen(_cl.get(Calendar.DAY_OF_MONTH), _cl.get(Calendar.MONTH) + 1, _cl.get(Calendar.YEAR));
}
public CalendarPopupScreen(int focusDay, int startMonth, int startYear) {
createScreen(focusDay, startMonth, startYear);
}
protected void onDisplay() {
if ( _initialFocusField != null ) {
_initialFocusField.setFocus();
_initialFocusField = null;
}
super.onDisplay();
}
private void createScreen(int focusDay, int startMonth, int startYear) {
_currentFocusDay = focusDay;
_currentMonth = startMonth;
_currentYear = startYear;
_normalFont = this.getFont().derive(Font.PLAIN);
if ( _normalFont.getAdvance(FIELD_SIZE_STRING) > Display.getWidth()/10 ) {
do {
_normalFont = _normalFont.derive(Font.PLAIN, _normalFont.getHeight()-1);
} while ( _normalFont.getAdvance(FIELD_SIZE_STRING) > Display.getWidth()/10 );
this.setFont(_normalFont);
}
_boldFont = _normalFont.derive(Font.BOLD);
HorizontalFieldManager hfm = new HorizontalFieldManager(HorizontalFieldManager.FIELD_HCENTER);
_prevMonthButton = new ButtonBorderedLabelField(SINGLE_BLANK + Characters.BLACK_LEFT_POINTING_TRIANGLE + SINGLE_BLANK,LabelField.FOCUSABLE);
hfm.add(_prevMonthButton);
_currentMonthField = new LabelField(SINGLE_BLANK + _currentMonthString + SINGLE_BLANK);
hfm.add(_currentMonthField);
_nextMonthButton = new ButtonBorderedLabelField(SINGLE_BLANK + Characters.BLACK_RIGHT_POINTING_TRIANGLE + SINGLE_BLANK,LabelField.FOCUSABLE);
hfm.add(_nextMonthButton);
this.add(hfm);
this.add(new VerticalSpacerField(3));
int columnSize = this.getFont().getAdvance(FIELD_SIZE_STRING);
for ( int i = 0; i < tableSizes.length; i++ ) {
tableSizes[i] = columnSize;
}
_monthManager = new TableLayoutManager(tableStyles, tableSizes, 0, TableLayoutManager.FIELD_HCENTER);
this.add(_monthManager);
this.setBorder(BorderFactory.createSimpleBorder(new XYEdges()));
displayMonth();
}
private void displayMonth() {
_monthManager.deleteAll();
_cl.set(Calendar.DAY_OF_MONTH, 1);
_cl.set(Calendar.MONTH, _currentMonth - 1);
_cl.set(Calendar.YEAR, _currentYear);
_cl.set(Calendar.HOUR_OF_DAY, 12);
_cl.set(Calendar.MINUTE, 0);
_cl.set(Calendar.SECOND, 0);
_cl.set(Calendar.MILLISECOND, 1);
long startOfMonth = _cl.getTime().getTime();
_currentMonthString = sdfMonth.formatLocal(_cl.getTime().getTime());
_currentMonthField.setText(SINGLE_BLANK + _currentMonthString + SINGLE_BLANK);
int workDay = _cl.get(Calendar.DAY_OF_WEEK);
int startAt = 0;
switch (workDay) {
case(Calendar.MONDAY): {
startAt = -1;
break;
}
case(Calendar.TUESDAY): {
startAt = -2;
break;
}
case(Calendar.WEDNESDAY): {
startAt = -3;
break;
}
case(Calendar.THURSDAY): {
startAt = -4;
break;
}
case(Calendar.FRIDAY): {
startAt = -5;
break;
}
case(Calendar.SATURDAY): {
startAt = -6;
break;
}
case(Calendar.SUNDAY): {
startAt = -6;
break;
}
}
Date workDate = _cl.getTime();
long workDateTime;
if(workDay==1){
workDateTime = workDate.getTime() + ((long)startAt);
}else{
workDateTime = workDate.getTime() + ((long)startAt) * ((long)DateTimeUtilities.ONEDAY);
}
long dayTime = workDateTime;
for ( int i = 0; i < 7; i++ ) {
String weekDay = sdfWeekDay.formatLocal(dayTime);
HeaderBorderedLabelField hblf = new HeaderBorderedLabelField(weekDay.substring(0,1), LabelField.USE_ALL_WIDTH | DrawStyle.HCENTER);
hblf.setFont(_boldFont);
_monthManager.add(hblf);
dayTime = dayTime + DateTimeUtilities.ONEDAY;
}
for ( int i = 0; i < 42; i++ ) {
workDate.setTime(workDateTime);
_cl.setTime(workDate);
workDateTime = workDateTime + DateTimeUtilities.ONEDAY;
BorderedLabelField blf = null;
int actualDate = _cl.get(Calendar.DAY_OF_MONTH);
String tempDateString = Integer.toString(actualDate);
if ( _cl.get(Calendar.MONTH) == _currentMonth - 1 ) {
blf = new BorderedLabelField(tempDateString, LabelField.USE_ALL_WIDTH | DrawStyle.HCENTER | LabelField.FOCUSABLE);
if ( _currentFocusDay == actualDate ) {
_initialFocusField = blf;
}
} else
if ( (i % 7 == 0) && (startOfMonth < _cl.getTime().getTime()) ) {
break;
} else {
blf = new UnfocusableBorderedLabelField(tempDateString, LabelField.USE_ALL_WIDTH | DrawStyle.HCENTER);
}
_monthManager.add(blf);
}
if ( this.isDisplayed() && _initialFocusField != null ) {
_initialFocusField.setFocus();
_initialFocusField = null;
}
}
public boolean keyChar(char key, int status, int time) {
boolean retval = false;
switch (key) {
case Characters.ENTER: {
processFocus();
retval = true;
break;
}
case Characters.ESCAPE: {
close();
retval = true;
break;
}
default:
retval = super.keyChar(key, status, time);
break;
}
return retval;
}
private boolean processFocus() {
// Should deal with whatever the focsu is currently on
Field focusField = this.getDelegate().getLeafFieldWithFocus();
if ( focusField instanceof ButtonBorderedLabelField ) {
_currentFocusDay = -1; // Leave focus on 'button'
_initialFocusField = focusField;
int monthIncrement = 33;
if ( focusField == _prevMonthButton ) {
monthIncrement = -3;
}
_cl.set(Calendar.DAY_OF_MONTH, 1);
_cl.set(Calendar.MONTH, _currentMonth-1);
_cl.set(Calendar.YEAR, _currentYear);
Date workDate = _cl.getTime();
workDate.setTime(workDate.getTime() + (((long)monthIncrement) * ((long)DateTimeUtilities.ONEDAY)));
_cl.setTime(workDate);
_currentMonth = _cl.get(Calendar.MONTH) + 1;
_currentYear = _cl.get(Calendar.YEAR);
displayMonth();
return true;
} else
if ( focusField instanceof BorderedLabelField ) {
LabelField lab = (LabelField) focusField;
_selectedDay = Integer.parseInt(lab.getText());
close();
return true;
}
return false;
}
protected boolean trackwheelClick( int status, int time ) {
if ( processFocus() ) {
Field focusField = this.getDelegate().getLeafFieldWithFocus();
if ( focusField instanceof ButtonBorderedLabelField ) {
}else{
Dialog.alert( getSelectedDate().getTime()+"");
}
return true;
}
return super.trackwheelClick(status, time);
}
public void close() {
UiApplication.getUiApplication().popScreen(this);
}
public Date getSelectedDate() {
if ( _selectedDay == -1 ) {
return null;
}
Calendar cl = Calendar.getInstance();
cl.set(Calendar.YEAR, _currentYear);
cl.set(Calendar.MONTH, _currentMonth - 1);
cl.set(Calendar.DAY_OF_MONTH, _selectedDay);
cl.set(Calendar.HOUR_OF_DAY, 0);
cl.set(Calendar.MINUTE, 0);
cl.set(Calendar.SECOND, 0);
cl.set(Calendar.MILLISECOND, 1);
return cl.getTime();
}
}
class BorderedLabelField extends LabelField {
int width;
int height;
public BorderedLabelField(String text, long style) {
super(text, style);
}
public void paint(Graphics g) {
super.paint(g);
width = this.getWidth();
height = this.getHeight();
g.drawRect(0, 0, width, height);
}
}
class HeaderBorderedLabelField extends BorderedLabelField {
public HeaderBorderedLabelField(String text, long style) {
super(text, style | LabelField.NON_FOCUSABLE);
}
public void paint(Graphics g) {
g.setBackgroundColor(Color.LIGHTBLUE);
g.clear();
super.paint(g);
}
}
class UnfocusableBorderedLabelField extends BorderedLabelField {
public UnfocusableBorderedLabelField(String text, long style) {
super(text, style | LabelField.NON_FOCUSABLE);
}
public void paint(Graphics g) {
g.setBackgroundColor(Color.LIGHTGREY);
g.clear();
super.paint(g);
}
}
class ButtonBorderedLabelField extends BorderedLabelField {
public ButtonBorderedLabelField(String text, long style) {
super(text, style);
}
public void paint(Graphics g) {
g.setBackgroundColor(Color.LIGHTGREEN);
g.clear();
super.paint(g);
}
}
class VerticalSpacerField extends Field {
// Only for VerticalFieldManagers
private int _height;
public VerticalSpacerField(int height) {
super(Field.NON_FOCUSABLE);
_height = height;
}
public void layout(int widht, int hieght) {
setExtent(10, _height);
}
public void paint(Graphics g) {
}
}
The TableLayoutManager class is given below -
public class TableLayoutManager extends Manager {
int _columnWidths[];
int _suggestedColumnWidths[];
int _rowHeights[];
int _columnStyles[];
public static final int USE_PREFERRED_SIZE = 1;
public static final int USE_PREFERRED_WIDTH_WITH_MAXIMUM = 2;
public static final int SPLIT_REMAINING_WIDTH = 4;
public static final int FIXED_WIDTH = 8;
private static int BITMASK_USE_PREFERRED = USE_PREFERRED_WIDTH_WITH_MAXIMUM | USE_PREFERRED_SIZE;
public static int DEFAULT_PADDING = 5;
int _rows;
int _columns;
private int _horizPadding;
public TableLayoutManager(int columnStyles[], long style) {
this(columnStyles, null, DEFAULT_PADDING, style);
}
public TableLayoutManager(int columnStyles[], int columnWidths[], long style) {
this(columnStyles, columnWidths, DEFAULT_PADDING, style);
}
public TableLayoutManager(int columnStyles[], int columnWidths[], int horizontalPadding, long style) {
super(style);
_horizPadding = horizontalPadding;
_columnStyles = columnStyles;
if (_columnStyles == null)
throw new IllegalArgumentException("not column styles");
if (columnWidths != null) {
_suggestedColumnWidths = Arrays.copy(columnWidths, 0, columnWidths.length);
if (_suggestedColumnWidths.length < _columnStyles.length) {
int oldLength = _suggestedColumnWidths.length;
int increase = columnStyles.length - oldLength;
_suggestedColumnWidths = Arrays.copy(columnWidths, 0, columnStyles.length);
Arrays.fill(_suggestedColumnWidths, 0, oldLength, increase);
}
} else
_suggestedColumnWidths = new int[_columnStyles.length];
}
private Field getField(int x, int y) {
int i = x + (y * _columns);
if (i >= getFieldCount())
return null;
return getField(i);
}
private boolean isColumnStyle(int value, int flag) {
return ((value) & (flag)) > 0;
}
public int getPreferredWidth() {
int numberFields = getFieldCount();
if (numberFields == 0)
return 0;
int rows = numberFields / _columnStyles.length;
int prefferedWidth = 0;
int styles[] = _columnStyles;
int[] columnWidths = new int[_columns];
Arrays.fill(columnWidths, -1);
for (int i = 0; i < _columns; i++) {
if (isColumnStyle(styles[i], FIXED_WIDTH)) {
columnWidths[i] = _suggestedColumnWidths[i];
} else {
if (isColumnStyle(styles[i], BITMASK_USE_PREFERRED)) {
for (int j = 0; j < rows; j++) {
Field field = getField(i, j);
if (field != null) {
int actualWidth = getPreferredWidthOfChild(field) + field.getMarginLeft() + field.getMarginRight();
if (isColumnStyle(styles[i], USE_PREFERRED_WIDTH_WITH_MAXIMUM)) {
actualWidth = Math.min(actualWidth, _suggestedColumnWidths[i]);
}
columnWidths[i] = Math.max(actualWidth, columnWidths[i]);
}
}
}
}
}
for (int n = 0; n < _columns; n++) {
prefferedWidth += columnWidths[n];
}
return prefferedWidth;
}
public int getPreferredHeight() {
int numberFields = getFieldCount();
if (numberFields == 0)
return 0;
int rows = numberFields / _columnStyles.length;
int prefferedHeight = 0;
int[] rowHeights = new int[rows];
Arrays.fill(rowHeights, -1);
for (int i = 0; i < _columns; i++) {
for (int j = 0; j < rows; j++) {
Field field = getField(i, j);
if (field != null) {
int actualHeight = getPreferredHeightOfChild(field) + field.getMarginBottom() + field.getMarginTop();
rowHeights[j] = Math.max(actualHeight, rowHeights[j]);
}
}
}
for (int n = 0; n < rows; n++) {
prefferedHeight += rowHeights[n];
}
return prefferedHeight;
}
protected void sublayout(int layoutWidth, int layoutHeight) {
int numberFields = getFieldCount();
if (numberFields == 0)
return;
layoutWidth -= getPaddingLeft() + getPaddingRight();
layoutHeight -= getPaddingTop() + getPaddingBottom();
_columns = _columnStyles.length;
int styles[] = _columnStyles;
if (isStyle(Field.USE_ALL_WIDTH)) {
boolean found = false;
for (int n = 0; n < _columns; n++) {
if (styles[n] == SPLIT_REMAINING_WIDTH) {
found = true;
break;
}
}
if (!found) {
styles[_columns - 1] = SPLIT_REMAINING_WIDTH;
}
}
_rows = numberFields / _columns;
if ((numberFields % _columns) > 0)
_rows++;
_columnWidths = new int[_columns];
_rowHeights = new int[_rows];
Arrays.fill(_columnWidths, -1);
Arrays.fill(_rowHeights, -1);
for (int i = 0; i < _columns; i++) {
if (isColumnStyle(styles[i], FIXED_WIDTH)) {
_columnWidths[i] = _suggestedColumnWidths[i];
} else {
if (isColumnStyle(styles[i], BITMASK_USE_PREFERRED)) {
for (int j = 0; j < _rows; j++) {
Field field = getField(i, j);
if (field != null) {
layoutChild(field, Math.max(0, layoutWidth - (field.getMarginLeft() + field.getMarginRight())),
Math.max(0, layoutHeight - (field.getMarginBottom() + field.getMarginTop())));
int actualWidth = getPreferredWidthOfChild(field) + field.getMarginLeft() + field.getMarginRight();
int actualHeight = getPreferredHeightOfChild(field) + field.getMarginBottom() + field.getMarginTop();
if (isColumnStyle(styles[i], USE_PREFERRED_WIDTH_WITH_MAXIMUM)) {
actualWidth = Math.min(actualWidth, _suggestedColumnWidths[i]);
}
_columnWidths[i] = Math.max(actualWidth, _columnWidths[i]);
_rowHeights[j] = Math.max(actualHeight, _rowHeights[j]);
}
}
}
}
}
int usedColumnWidth = 0;
int numUnassignedColumnWidths = 0;
for (int i = 0; i < _columns; i++) {
if (_columnWidths[i] >= 0) {
usedColumnWidth += _columnWidths[i] + ((i < (_columns - 1)) ? _horizPadding : 0);
} else {
numUnassignedColumnWidths++;
}
}
if (numUnassignedColumnWidths > 0) {
int remainingWidthToAssign = layoutWidth - usedColumnWidth;
if (remainingWidthToAssign < 0) {
remainingWidthToAssign = 0;
}
int splitRemainingWidth = (remainingWidthToAssign - ((numUnassignedColumnWidths - 1) * _horizPadding))
/ numUnassignedColumnWidths;
for (int i = 0; i < _columns; i++) {
int assignedWidth = Math.min(remainingWidthToAssign,
splitRemainingWidth);
if (_columnWidths[i] < 0) {
_columnWidths[i] = assignedWidth;
remainingWidthToAssign -= assignedWidth;
}
}
}
int currentRow = 0;
int currentColumn = 0;
int y = getPaddingTop();
for (int n = 0; n < numberFields; n++) {
Field field = getField(n);
if (!isColumnStyle(styles[currentColumn], USE_PREFERRED_SIZE)) {
layoutChild( field,
Math.max(0, _columnWidths[currentColumn] - (field.getMarginLeft() + field.getMarginRight())),
Math.max(0, layoutHeight - y - (field.getMarginBottom() + field.getMarginTop())));
}
_rowHeights[currentRow] =Math.max(_rowHeights[currentRow], field.getExtent().height + field.getMarginBottom() + field.getMarginTop());
currentColumn++;
if ((n == (numberFields - 1)) || (currentColumn >= _columns)) {
int x = getPaddingLeft();
for (int i = 0; i < currentColumn; i++) {
Field field1 = getField(i, currentRow);
XYPoint offset = calcAlignmentOffset(field1,
Math.max( 0, _columnWidths[i] - (field1.getMarginLeft() + field1.getMarginRight())),
Math.max(0, _rowHeights[currentRow] - (field1.getMarginBottom() + field1.getMarginTop())));
setPositionChild(field1, x + offset.x + field1.getMarginLeft(), y + offset.y + field1.getMarginTop());
x += _columnWidths[i] + _horizPadding;
}
y += _rowHeights[currentRow];
currentColumn = 0;
currentRow++;
}
}
int totalWidth = 0;
if (isStyle(Field.USE_ALL_WIDTH)) {
totalWidth = layoutWidth;
} else {
for (int i = 0; i < _columns; i++) {
totalWidth += _columnWidths[i] + ((i < (_columns - 1)) ? _horizPadding : 0);
}
}
totalWidth += getPaddingLeft() + getPaddingRight();
y += getPaddingBottom();
setExtent(totalWidth, Math.min(y, layoutHeight));
}
protected boolean navigationMovement(int dx, int dy, int status, int time) {
int focusIndex = getFieldWithFocusIndex();
int dirY = (dy > 0) ? 1 : -1;
int absY = Math.abs(dy);
for (int y = 0; y < absY; y++) {
focusIndex += _columns * dirY;
if (focusIndex < 0 || focusIndex >= getFieldCount()) {
return false;
} else {
Field f = getField(focusIndex);
if (f.isFocusable()) {
f.setFocus();
} else
y--;
}
}
int dirX = (dx > 0) ? 1 : -1;
int absX = Math.abs(dx);
for (int x = 0; x < absX; x++) {
focusIndex += dirX;
if (focusIndex < 0 || focusIndex >= getFieldCount()) {
return false;
} else {
Field f = getField(focusIndex);
if (f.isFocusable()) {
f.setFocus();
} else
x--;
}
}
return true;
}
private XYPoint calcAlignmentOffset(Field field, int width, int height) {
XYPoint offset = new XYPoint(0, 0);
long fieldStyle = field.getStyle();
long field_x_style = fieldStyle & Field.FIELD_HALIGN_MASK;
if (field_x_style == Field.FIELD_RIGHT) {
offset.x = width - field.getExtent().width;
} else if (field_x_style == Field.FIELD_HCENTER) {
offset.x = (width - field.getExtent().width) / 2;
}
long field_y_style = fieldStyle & Field.FIELD_VALIGN_MASK;
if (field_y_style == Field.FIELD_BOTTOM) {
offset.y = height - field.getExtent().height;
} else if (field_y_style == Field.FIELD_VCENTER) {
offset.y = (height - field.getExtent().height) / 2;
}
return offset;
}
}
public class CalendarPopupScreen extends MainScreen {
private static SimpleDateFormat sdfWeekDay = new SimpleDateFormat("E");
private static SimpleDateFormat sdfMonth = new SimpleDateFormat("MMMM yyyy");
private static String SINGLE_BLANK = " ";
private static String FIELD_SIZE_STRING = " 30 ";
private int _selectedDay = -1;
private int _currentFocusDay;
private int _currentMonth;
private String _currentMonthString;
private int _currentYear;
private Calendar _cl = Calendar.getInstance();
private ButtonBorderedLabelField _prevMonthButton;
private LabelField _currentMonthField;
private ButtonBorderedLabelField _nextMonthButton;
private static int [] tableStyles = new int [] {
TableLayoutManager.FIXED_WIDTH,
TableLayoutManager.FIXED_WIDTH,
TableLayoutManager.FIXED_WIDTH,
TableLayoutManager.FIXED_WIDTH,
TableLayoutManager.FIXED_WIDTH,
TableLayoutManager.FIXED_WIDTH,
TableLayoutManager.FIXED_WIDTH
};
private int [] tableSizes = new int [7] ;
private TableLayoutManager _monthManager;
private Field _initialFocusField = null;
private Font _normalFont;
private Font _boldFont;
public CalendarPopupScreen() {
this(new Date());
}
public CalendarPopupScreen(long dateMilliSecs) {
this(new Date(dateMilliSecs));
}
public CalendarPopupScreen(Date selectedDate) {
_cl.setTime(selectedDate);
createScreen(_cl.get(Calendar.DAY_OF_MONTH), _cl.get(Calendar.MONTH) + 1, _cl.get(Calendar.YEAR));
}
public CalendarPopupScreen(int focusDay, int startMonth, int startYear) {
createScreen(focusDay, startMonth, startYear);
}
protected void onDisplay() {
if ( _initialFocusField != null ) {
_initialFocusField.setFocus();
_initialFocusField = null;
}
super.onDisplay();
}
private void createScreen(int focusDay, int startMonth, int startYear) {
_currentFocusDay = focusDay;
_currentMonth = startMonth;
_currentYear = startYear;
_normalFont = this.getFont().derive(Font.PLAIN);
if ( _normalFont.getAdvance(FIELD_SIZE_STRING) > Display.getWidth()/10 ) {
do {
_normalFont = _normalFont.derive(Font.PLAIN, _normalFont.getHeight()-1);
} while ( _normalFont.getAdvance(FIELD_SIZE_STRING) > Display.getWidth()/10 );
this.setFont(_normalFont);
}
_boldFont = _normalFont.derive(Font.BOLD);
HorizontalFieldManager hfm = new HorizontalFieldManager(HorizontalFieldManager.FIELD_HCENTER);
_prevMonthButton = new ButtonBorderedLabelField(SINGLE_BLANK + Characters.BLACK_LEFT_POINTING_TRIANGLE + SINGLE_BLANK,LabelField.FOCUSABLE);
hfm.add(_prevMonthButton);
_currentMonthField = new LabelField(SINGLE_BLANK + _currentMonthString + SINGLE_BLANK);
hfm.add(_currentMonthField);
_nextMonthButton = new ButtonBorderedLabelField(SINGLE_BLANK + Characters.BLACK_RIGHT_POINTING_TRIANGLE + SINGLE_BLANK,LabelField.FOCUSABLE);
hfm.add(_nextMonthButton);
this.add(hfm);
this.add(new VerticalSpacerField(3));
int columnSize = this.getFont().getAdvance(FIELD_SIZE_STRING);
for ( int i = 0; i < tableSizes.length; i++ ) {
tableSizes[i] = columnSize;
}
_monthManager = new TableLayoutManager(tableStyles, tableSizes, 0, TableLayoutManager.FIELD_HCENTER);
this.add(_monthManager);
this.setBorder(BorderFactory.createSimpleBorder(new XYEdges()));
displayMonth();
}
private void displayMonth() {
_monthManager.deleteAll();
_cl.set(Calendar.DAY_OF_MONTH, 1);
_cl.set(Calendar.MONTH, _currentMonth - 1);
_cl.set(Calendar.YEAR, _currentYear);
_cl.set(Calendar.HOUR_OF_DAY, 12);
_cl.set(Calendar.MINUTE, 0);
_cl.set(Calendar.SECOND, 0);
_cl.set(Calendar.MILLISECOND, 1);
long startOfMonth = _cl.getTime().getTime();
_currentMonthString = sdfMonth.formatLocal(_cl.getTime().getTime());
_currentMonthField.setText(SINGLE_BLANK + _currentMonthString + SINGLE_BLANK);
int workDay = _cl.get(Calendar.DAY_OF_WEEK);
int startAt = 0;
switch (workDay) {
case(Calendar.MONDAY): {
startAt = -1;
break;
}
case(Calendar.TUESDAY): {
startAt = -2;
break;
}
case(Calendar.WEDNESDAY): {
startAt = -3;
break;
}
case(Calendar.THURSDAY): {
startAt = -4;
break;
}
case(Calendar.FRIDAY): {
startAt = -5;
break;
}
case(Calendar.SATURDAY): {
startAt = -6;
break;
}
case(Calendar.SUNDAY): {
startAt = -6;
break;
}
}
Date workDate = _cl.getTime();
long workDateTime;
if(workDay==1){
workDateTime = workDate.getTime() + ((long)startAt);
}else{
workDateTime = workDate.getTime() + ((long)startAt) * ((long)DateTimeUtilities.ONEDAY);
}
long dayTime = workDateTime;
for ( int i = 0; i < 7; i++ ) {
String weekDay = sdfWeekDay.formatLocal(dayTime);
HeaderBorderedLabelField hblf = new HeaderBorderedLabelField(weekDay.substring(0,1), LabelField.USE_ALL_WIDTH | DrawStyle.HCENTER);
hblf.setFont(_boldFont);
_monthManager.add(hblf);
dayTime = dayTime + DateTimeUtilities.ONEDAY;
}
for ( int i = 0; i < 42; i++ ) {
workDate.setTime(workDateTime);
_cl.setTime(workDate);
workDateTime = workDateTime + DateTimeUtilities.ONEDAY;
BorderedLabelField blf = null;
int actualDate = _cl.get(Calendar.DAY_OF_MONTH);
String tempDateString = Integer.toString(actualDate);
if ( _cl.get(Calendar.MONTH) == _currentMonth - 1 ) {
blf = new BorderedLabelField(tempDateString, LabelField.USE_ALL_WIDTH | DrawStyle.HCENTER | LabelField.FOCUSABLE);
if ( _currentFocusDay == actualDate ) {
_initialFocusField = blf;
}
} else
if ( (i % 7 == 0) && (startOfMonth < _cl.getTime().getTime()) ) {
break;
} else {
blf = new UnfocusableBorderedLabelField(tempDateString, LabelField.USE_ALL_WIDTH | DrawStyle.HCENTER);
}
_monthManager.add(blf);
}
if ( this.isDisplayed() && _initialFocusField != null ) {
_initialFocusField.setFocus();
_initialFocusField = null;
}
}
public boolean keyChar(char key, int status, int time) {
boolean retval = false;
switch (key) {
case Characters.ENTER: {
processFocus();
retval = true;
break;
}
case Characters.ESCAPE: {
close();
retval = true;
break;
}
default:
retval = super.keyChar(key, status, time);
break;
}
return retval;
}
private boolean processFocus() {
// Should deal with whatever the focsu is currently on
Field focusField = this.getDelegate().getLeafFieldWithFocus();
if ( focusField instanceof ButtonBorderedLabelField ) {
_currentFocusDay = -1; // Leave focus on 'button'
_initialFocusField = focusField;
int monthIncrement = 33;
if ( focusField == _prevMonthButton ) {
monthIncrement = -3;
}
_cl.set(Calendar.DAY_OF_MONTH, 1);
_cl.set(Calendar.MONTH, _currentMonth-1);
_cl.set(Calendar.YEAR, _currentYear);
Date workDate = _cl.getTime();
workDate.setTime(workDate.getTime() + (((long)monthIncrement) * ((long)DateTimeUtilities.ONEDAY)));
_cl.setTime(workDate);
_currentMonth = _cl.get(Calendar.MONTH) + 1;
_currentYear = _cl.get(Calendar.YEAR);
displayMonth();
return true;
} else
if ( focusField instanceof BorderedLabelField ) {
LabelField lab = (LabelField) focusField;
_selectedDay = Integer.parseInt(lab.getText());
close();
return true;
}
return false;
}
protected boolean trackwheelClick( int status, int time ) {
if ( processFocus() ) {
Field focusField = this.getDelegate().getLeafFieldWithFocus();
if ( focusField instanceof ButtonBorderedLabelField ) {
}else{
Dialog.alert( getSelectedDate().getTime()+"");
}
return true;
}
return super.trackwheelClick(status, time);
}
public void close() {
UiApplication.getUiApplication().popScreen(this);
}
public Date getSelectedDate() {
if ( _selectedDay == -1 ) {
return null;
}
Calendar cl = Calendar.getInstance();
cl.set(Calendar.YEAR, _currentYear);
cl.set(Calendar.MONTH, _currentMonth - 1);
cl.set(Calendar.DAY_OF_MONTH, _selectedDay);
cl.set(Calendar.HOUR_OF_DAY, 0);
cl.set(Calendar.MINUTE, 0);
cl.set(Calendar.SECOND, 0);
cl.set(Calendar.MILLISECOND, 1);
return cl.getTime();
}
}
class BorderedLabelField extends LabelField {
int width;
int height;
public BorderedLabelField(String text, long style) {
super(text, style);
}
public void paint(Graphics g) {
super.paint(g);
width = this.getWidth();
height = this.getHeight();
g.drawRect(0, 0, width, height);
}
}
class HeaderBorderedLabelField extends BorderedLabelField {
public HeaderBorderedLabelField(String text, long style) {
super(text, style | LabelField.NON_FOCUSABLE);
}
public void paint(Graphics g) {
g.setBackgroundColor(Color.LIGHTBLUE);
g.clear();
super.paint(g);
}
}
class UnfocusableBorderedLabelField extends BorderedLabelField {
public UnfocusableBorderedLabelField(String text, long style) {
super(text, style | LabelField.NON_FOCUSABLE);
}
public void paint(Graphics g) {
g.setBackgroundColor(Color.LIGHTGREY);
g.clear();
super.paint(g);
}
}
class ButtonBorderedLabelField extends BorderedLabelField {
public ButtonBorderedLabelField(String text, long style) {
super(text, style);
}
public void paint(Graphics g) {
g.setBackgroundColor(Color.LIGHTGREEN);
g.clear();
super.paint(g);
}
}
class VerticalSpacerField extends Field {
// Only for VerticalFieldManagers
private int _height;
public VerticalSpacerField(int height) {
super(Field.NON_FOCUSABLE);
_height = height;
}
public void layout(int widht, int hieght) {
setExtent(10, _height);
}
public void paint(Graphics g) {
}
}
The TableLayoutManager class is given below -
public class TableLayoutManager extends Manager {
int _columnWidths[];
int _suggestedColumnWidths[];
int _rowHeights[];
int _columnStyles[];
public static final int USE_PREFERRED_SIZE = 1;
public static final int USE_PREFERRED_WIDTH_WITH_MAXIMUM = 2;
public static final int SPLIT_REMAINING_WIDTH = 4;
public static final int FIXED_WIDTH = 8;
private static int BITMASK_USE_PREFERRED = USE_PREFERRED_WIDTH_WITH_MAXIMUM | USE_PREFERRED_SIZE;
public static int DEFAULT_PADDING = 5;
int _rows;
int _columns;
private int _horizPadding;
public TableLayoutManager(int columnStyles[], long style) {
this(columnStyles, null, DEFAULT_PADDING, style);
}
public TableLayoutManager(int columnStyles[], int columnWidths[], long style) {
this(columnStyles, columnWidths, DEFAULT_PADDING, style);
}
public TableLayoutManager(int columnStyles[], int columnWidths[], int horizontalPadding, long style) {
super(style);
_horizPadding = horizontalPadding;
_columnStyles = columnStyles;
if (_columnStyles == null)
throw new IllegalArgumentException("not column styles");
if (columnWidths != null) {
_suggestedColumnWidths = Arrays.copy(columnWidths, 0, columnWidths.length);
if (_suggestedColumnWidths.length < _columnStyles.length) {
int oldLength = _suggestedColumnWidths.length;
int increase = columnStyles.length - oldLength;
_suggestedColumnWidths = Arrays.copy(columnWidths, 0, columnStyles.length);
Arrays.fill(_suggestedColumnWidths, 0, oldLength, increase);
}
} else
_suggestedColumnWidths = new int[_columnStyles.length];
}
private Field getField(int x, int y) {
int i = x + (y * _columns);
if (i >= getFieldCount())
return null;
return getField(i);
}
private boolean isColumnStyle(int value, int flag) {
return ((value) & (flag)) > 0;
}
public int getPreferredWidth() {
int numberFields = getFieldCount();
if (numberFields == 0)
return 0;
int rows = numberFields / _columnStyles.length;
int prefferedWidth = 0;
int styles[] = _columnStyles;
int[] columnWidths = new int[_columns];
Arrays.fill(columnWidths, -1);
for (int i = 0; i < _columns; i++) {
if (isColumnStyle(styles[i], FIXED_WIDTH)) {
columnWidths[i] = _suggestedColumnWidths[i];
} else {
if (isColumnStyle(styles[i], BITMASK_USE_PREFERRED)) {
for (int j = 0; j < rows; j++) {
Field field = getField(i, j);
if (field != null) {
int actualWidth = getPreferredWidthOfChild(field) + field.getMarginLeft() + field.getMarginRight();
if (isColumnStyle(styles[i], USE_PREFERRED_WIDTH_WITH_MAXIMUM)) {
actualWidth = Math.min(actualWidth, _suggestedColumnWidths[i]);
}
columnWidths[i] = Math.max(actualWidth, columnWidths[i]);
}
}
}
}
}
for (int n = 0; n < _columns; n++) {
prefferedWidth += columnWidths[n];
}
return prefferedWidth;
}
public int getPreferredHeight() {
int numberFields = getFieldCount();
if (numberFields == 0)
return 0;
int rows = numberFields / _columnStyles.length;
int prefferedHeight = 0;
int[] rowHeights = new int[rows];
Arrays.fill(rowHeights, -1);
for (int i = 0; i < _columns; i++) {
for (int j = 0; j < rows; j++) {
Field field = getField(i, j);
if (field != null) {
int actualHeight = getPreferredHeightOfChild(field) + field.getMarginBottom() + field.getMarginTop();
rowHeights[j] = Math.max(actualHeight, rowHeights[j]);
}
}
}
for (int n = 0; n < rows; n++) {
prefferedHeight += rowHeights[n];
}
return prefferedHeight;
}
protected void sublayout(int layoutWidth, int layoutHeight) {
int numberFields = getFieldCount();
if (numberFields == 0)
return;
layoutWidth -= getPaddingLeft() + getPaddingRight();
layoutHeight -= getPaddingTop() + getPaddingBottom();
_columns = _columnStyles.length;
int styles[] = _columnStyles;
if (isStyle(Field.USE_ALL_WIDTH)) {
boolean found = false;
for (int n = 0; n < _columns; n++) {
if (styles[n] == SPLIT_REMAINING_WIDTH) {
found = true;
break;
}
}
if (!found) {
styles[_columns - 1] = SPLIT_REMAINING_WIDTH;
}
}
_rows = numberFields / _columns;
if ((numberFields % _columns) > 0)
_rows++;
_columnWidths = new int[_columns];
_rowHeights = new int[_rows];
Arrays.fill(_columnWidths, -1);
Arrays.fill(_rowHeights, -1);
for (int i = 0; i < _columns; i++) {
if (isColumnStyle(styles[i], FIXED_WIDTH)) {
_columnWidths[i] = _suggestedColumnWidths[i];
} else {
if (isColumnStyle(styles[i], BITMASK_USE_PREFERRED)) {
for (int j = 0; j < _rows; j++) {
Field field = getField(i, j);
if (field != null) {
layoutChild(field, Math.max(0, layoutWidth - (field.getMarginLeft() + field.getMarginRight())),
Math.max(0, layoutHeight - (field.getMarginBottom() + field.getMarginTop())));
int actualWidth = getPreferredWidthOfChild(field) + field.getMarginLeft() + field.getMarginRight();
int actualHeight = getPreferredHeightOfChild(field) + field.getMarginBottom() + field.getMarginTop();
if (isColumnStyle(styles[i], USE_PREFERRED_WIDTH_WITH_MAXIMUM)) {
actualWidth = Math.min(actualWidth, _suggestedColumnWidths[i]);
}
_columnWidths[i] = Math.max(actualWidth, _columnWidths[i]);
_rowHeights[j] = Math.max(actualHeight, _rowHeights[j]);
}
}
}
}
}
int usedColumnWidth = 0;
int numUnassignedColumnWidths = 0;
for (int i = 0; i < _columns; i++) {
if (_columnWidths[i] >= 0) {
usedColumnWidth += _columnWidths[i] + ((i < (_columns - 1)) ? _horizPadding : 0);
} else {
numUnassignedColumnWidths++;
}
}
if (numUnassignedColumnWidths > 0) {
int remainingWidthToAssign = layoutWidth - usedColumnWidth;
if (remainingWidthToAssign < 0) {
remainingWidthToAssign = 0;
}
int splitRemainingWidth = (remainingWidthToAssign - ((numUnassignedColumnWidths - 1) * _horizPadding))
/ numUnassignedColumnWidths;
for (int i = 0; i < _columns; i++) {
int assignedWidth = Math.min(remainingWidthToAssign,
splitRemainingWidth);
if (_columnWidths[i] < 0) {
_columnWidths[i] = assignedWidth;
remainingWidthToAssign -= assignedWidth;
}
}
}
int currentRow = 0;
int currentColumn = 0;
int y = getPaddingTop();
for (int n = 0; n < numberFields; n++) {
Field field = getField(n);
if (!isColumnStyle(styles[currentColumn], USE_PREFERRED_SIZE)) {
layoutChild( field,
Math.max(0, _columnWidths[currentColumn] - (field.getMarginLeft() + field.getMarginRight())),
Math.max(0, layoutHeight - y - (field.getMarginBottom() + field.getMarginTop())));
}
_rowHeights[currentRow] =Math.max(_rowHeights[currentRow], field.getExtent().height + field.getMarginBottom() + field.getMarginTop());
currentColumn++;
if ((n == (numberFields - 1)) || (currentColumn >= _columns)) {
int x = getPaddingLeft();
for (int i = 0; i < currentColumn; i++) {
Field field1 = getField(i, currentRow);
XYPoint offset = calcAlignmentOffset(field1,
Math.max( 0, _columnWidths[i] - (field1.getMarginLeft() + field1.getMarginRight())),
Math.max(0, _rowHeights[currentRow] - (field1.getMarginBottom() + field1.getMarginTop())));
setPositionChild(field1, x + offset.x + field1.getMarginLeft(), y + offset.y + field1.getMarginTop());
x += _columnWidths[i] + _horizPadding;
}
y += _rowHeights[currentRow];
currentColumn = 0;
currentRow++;
}
}
int totalWidth = 0;
if (isStyle(Field.USE_ALL_WIDTH)) {
totalWidth = layoutWidth;
} else {
for (int i = 0; i < _columns; i++) {
totalWidth += _columnWidths[i] + ((i < (_columns - 1)) ? _horizPadding : 0);
}
}
totalWidth += getPaddingLeft() + getPaddingRight();
y += getPaddingBottom();
setExtent(totalWidth, Math.min(y, layoutHeight));
}
protected boolean navigationMovement(int dx, int dy, int status, int time) {
int focusIndex = getFieldWithFocusIndex();
int dirY = (dy > 0) ? 1 : -1;
int absY = Math.abs(dy);
for (int y = 0; y < absY; y++) {
focusIndex += _columns * dirY;
if (focusIndex < 0 || focusIndex >= getFieldCount()) {
return false;
} else {
Field f = getField(focusIndex);
if (f.isFocusable()) {
f.setFocus();
} else
y--;
}
}
int dirX = (dx > 0) ? 1 : -1;
int absX = Math.abs(dx);
for (int x = 0; x < absX; x++) {
focusIndex += dirX;
if (focusIndex < 0 || focusIndex >= getFieldCount()) {
return false;
} else {
Field f = getField(focusIndex);
if (f.isFocusable()) {
f.setFocus();
} else
x--;
}
}
return true;
}
private XYPoint calcAlignmentOffset(Field field, int width, int height) {
XYPoint offset = new XYPoint(0, 0);
long fieldStyle = field.getStyle();
long field_x_style = fieldStyle & Field.FIELD_HALIGN_MASK;
if (field_x_style == Field.FIELD_RIGHT) {
offset.x = width - field.getExtent().width;
} else if (field_x_style == Field.FIELD_HCENTER) {
offset.x = (width - field.getExtent().width) / 2;
}
long field_y_style = fieldStyle & Field.FIELD_VALIGN_MASK;
if (field_y_style == Field.FIELD_BOTTOM) {
offset.y = height - field.getExtent().height;
} else if (field_y_style == Field.FIELD_VCENTER) {
offset.y = (height - field.getExtent().height) / 2;
}
return offset;
}
}
Subscribe to:
Posts (Atom)