I can't align text on the BlackBerry screen. I've tried using a LabelField or a RichTextField but the text is not getting aligned the way I want. It is aligned horizontally and hidden in the screen. I want the text to wrap on the next line, when it hits the end of the screen horizontally, rather than getting hidden.
Here is my code -
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
public class DetailBloodBank extends MainScreen
{
String resultData = "", location = "", phoneNumber = "";
LabelField bloodBankName, locationLabel, phoneNumLabel;
String bloodBank = "";
LabelField locationDetail, phoneNumDetail;
public DetailBloodBank(String data) {
super(NO_VERTICAL_SCROLL);
int height = Display.getHeight();
int widhth = Display.getWidth();
//SizedVFM horizontalFieldManager = new SizedVFM(widhth,height);
HorizontalFieldManager horizontalFieldManager = new HorizontalFieldManager(HorizontalFieldManager.NO_VERTICAL_SCROLL)
{
protected void paint(Graphics g) {
g.setBackgroundColor(Color.BLACK);
g.clear();
super.paint(g);
}
};
//setBanner(horizontalFieldManager);
resultData = data;
System.out.println(resultData);
bloodBankName = new LabelField(resultData)
{
public void paint(Graphics g) {
g.setColor(Color.WHITE);
super.paint(g);
}
};
Font font = Font.getDefault().derive(Font.BOLD, 8, Ui.UNITS_pt);
bloodBankName.setFont(font);
locationLabel = new LabelField("Location")
{
public void paint(Graphics g) {
g.setColor(Color.WHITE);
super.paint(g);
}
};
Font font2 = Font.getDefault().derive(Font.BOLD, 8, Ui.UNITS_pt);
locationLabel.setFont(font2);
phoneNumLabel = new LabelField("Phone Number")
{
public void paint(Graphics g) {
g.setColor(Color.WHITE);
super.paint(g);
}
};
Font font3 = Font.getDefault().derive(Font.BOLD, 8, Ui.UNITS_pt);
phoneNumLabel.setFont(font3);
DBHelpers dbh = new DBHelpers();
dbh.retrieveDetails(resultData);
location = dbh.getLocation();
phoneNumber = dbh.getPhoneNumber();
dbh.getConnectionClose();
phoneNumDetail = new LabelField(phoneNumber)
{
public void paint(Graphics g) {
g.setColor(Color.WHITE);
super.paint(g);
}
};
Font font4 = Font.getDefault().derive(Font.PLAIN, 6, Ui.UNITS_pt);
phoneNumDetail.setFont(font4);
locationDetail = new LabelField(location)
{
public void paint(Graphics g) {
g.setColor(Color.WHITE);
super.paint(g);
}
};
Font font5 = Font.getDefault().derive(Font.PLAIN, 6, Ui.UNITS_pt);
locationDetail.setFont(font5);
final SeparatorField sepfield2 = new SeparatorField(SeparatorField.LINE_HORIZONTAL | Field.USE_ALL_WIDTH)
{
protected void paint(Graphics g) {
g.setBackgroundColor(Color.WHITE);
g.clear();
super.paint(g);
}
protected void layout(int maxWidth, int maxHeight) {
int width = Display.getWidth();
int height = 25; //height of the manager
super.layout(1250, 15);
}
};
final VerticalFieldManager verticalFieldManager = new VerticalFieldManager(NO_HORIZONTAL_SCROLL);
verticalFieldManager.add(locationLabel);
verticalFieldManager.add(locationDetail);
final VerticalFieldManager verticalFieldManager2 = new VerticalFieldManager(NO_HORIZONTAL_SCROLL);
verticalFieldManager2.add(phoneNumLabel);
verticalFieldManager2.add(phoneNumDetail);
VerticalFieldManager routeManager2 = new VerticalFieldManager()
{
protected void sublayout(int width, int height) {
layoutChild(bloodBankName, getPreferredWidth(), getPreferredHeight());
layoutChild(sepfield2, getPreferredWidth(), getPreferredHeight());
layoutChild(verticalFieldManager, getPreferredWidth(), getPreferredHeight());
layoutChild(verticalFieldManager2, getPreferredWidth(), getPreferredHeight());
setPositionChild(bloodBankName, 5, 15);
setPositionChild(sepfield2, 0, 35);
setPositionChild(verticalFieldManager, 0, 72);
int y = verticalFieldManager.getHeight();
System.out.println(y);
setPositionChild(verticalFieldManager2, 0, y + 90);
super.setExtent(width, height);
}
};
routeManager2.add(bloodBankName);
routeManager2.add(sepfield2);
routeManager2.add(verticalFieldManager);
routeManager2.add(verticalFieldManager2);
horizontalFieldManager.add(routeManager2);
add(horizontalFieldManager);
}
}
The problem is with your layout logic in routeManager2.
layoutChild(bloodBankName, getPreferredWidth(), getPreferredHeight());
The preferred width of the LabelField or RichTextField is going to be the width of the String associated with it in the current font size. It would prefer to show everything on one line if possible. So, instead of passing its preference, pass the width provided to sublayout(int, int).
layoutChild(bloodBankName, width, getPreferredHeight());
Hope this helps.
Related
Hi all thanks to read my answer hope you can help me
I am working on Image cropping in blackberry. In my application contain 3 main things.
1)Load the image on the screen
2)select the shape of the cropping area
3)display that cropping image on next screen with out losing its shape
Step1: i can done the image loading part
step2: using Menu i just add the 4 types of shapes
1)Circle
2)Rectangle with rounded shape
3)Star
4)Cloud
using menu when he click on any menu item ,then that particular shape image will display on the screen.
we can give the movement to that image because we have to provide him to select any portion of the image.
step3: After fix the position then we will allow the user to crop using menu.
when he click on menu item " CROP". then we have to crop the image according the shape and that image should display on the next screen
Note: Following code working only for Rectangular shape but i want to
use all shapes
This is my sample code ::
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.XYEdges;
import net.rim.device.api.ui.XYRect;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.decor.BackgroundFactory;
public class ClipMove extends MainScreen{
Bitmap circle_frame,rectangle_frame,star_frame,cloud_frame,image,selected_frame;
BitmapField frmae_field;
private int padding_x=0,padding_y=0;
private VerticalFieldManager vrt_mgr;
public ClipMove() {
//Here my shape images are transparent
circle_frame=Bitmap.getBitmapResource("circle.gif");
rectangle_frame=Bitmap.getBitmapResource("rect1.png");
star_frame=Bitmap.getBitmapResource("star.gif");
cloud_frame=Bitmap.getBitmapResource("cloud.gif");
//this is my actual image to crop
image=Bitmap.getBitmapResource("sample.jpg");
vrt_mgr=new VerticalFieldManager(){
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout(Display.getWidth(),Display.getHeight());
setExtent(Display.getWidth(),Display.getHeight());
}
};
vrt_mgr.setBackground(BackgroundFactory.createBitmapBackground(image));
add(vrt_mgr);
}
protected void makeMenu(Menu menu, int instance) {
super.makeMenu(menu, instance);
menu.add(new MenuItem("Rect",0,0) {
public void run() {
// TODO Auto-generated method stub
vrt_mgr.deleteAll();
selected_frame=rectangle_frame;
frmae_field=new BitmapField(rectangle_frame);
vrt_mgr.add(frmae_field);
vrt_mgr.invalidate();
}
});
menu.add(new MenuItem("Circle",0,0) {
public void run() {
// TODO Auto-generated method stub
vrt_mgr.deleteAll();
selected_frame=circle_frame;
frmae_field=new BitmapField(circle_frame);
vrt_mgr.add(frmae_field);
vrt_mgr.invalidate();
}
});
menu.add(new MenuItem("Star",0,0) {
public void run() {
// TODO Auto-generated method stub
vrt_mgr.deleteAll();
selected_frame=star_frame;
frmae_field=new BitmapField(star_frame);
vrt_mgr.add(frmae_field);
vrt_mgr.invalidate();
}
});
menu.add(new MenuItem("Cloud",0,0) {
public void run() {
// TODO Auto-generated method stub
vrt_mgr.deleteAll();
selected_frame=cloud_frame;
frmae_field=new BitmapField(cloud_frame);
vrt_mgr.add(frmae_field);
vrt_mgr.invalidate();
}
});
menu.add(new MenuItem("Crop",0,0) {
public void run() {
// TODO Auto-generated method stub
Field f=vrt_mgr.getField(0);
// XYRect rect=getFieldExtent(f);
XYRect rect=new XYRect(padding_x, padding_y,frmae_field.getBitmapWidth(),frmae_field.getBitmapHeight());
Bitmap crop = cropImage(image, rect.x, rect.y,
rect.width, rect.height);
synchronized (UiApplication.getEventLock()) {
UiApplication.getUiApplication().pushScreen(new sampleScreen(crop,selected_frame));
}
}
});
}
protected boolean navigationMovement(int dx, int dy, int status, int time) {
if(frmae_field!=null){
padding_x=padding_x+dx;
padding_y=padding_y+dy;
XYEdges edge=new XYEdges(padding_y, 0, 0, padding_x);
frmae_field.setPadding(edge);
vrt_mgr.invalidate();
return true;
}else {
return false;
}
}
public void DisplayMessage(final String str)
{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.inform(str);
}
});
}
public XYRect getFieldExtent(Field fld) {
int cy = fld.getContentTop();
int cx = fld.getContentLeft();
Manager m = fld.getManager();
while (m != null) {
cy += m.getContentTop() - m.getVerticalScroll();
cx += m.getContentLeft() - m.getHorizontalScroll();
if (m instanceof Screen)
break;
m = m.getManager();
}
return new XYRect(cx, cy, fld.getContentWidth(), fld.getContentHeight());
}
// this logic only useful for rectangler shape
public Bitmap cropImage(Bitmap image, int x, int y, int width,int height) {
Bitmap result = new Bitmap(width, height);
Graphics g = Graphics.create(result);
g.drawBitmap(0, 0, width, height, image, x, y);
return result;
}
}
//this is my next screen to show the croped image
class sampleScreen extends MainScreen
{
VerticalFieldManager manager;
public sampleScreen(final Bitmap img,final Bitmap back) {
manager=new VerticalFieldManager(){
protected void paint(Graphics graphics) {
graphics.drawBitmap(0, 0, img.getWidth(), img.getHeight(), img, 0, 0);
super.paint(graphics);
}
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout( img.getWidth(), img.getHeight());
setExtent( img.getWidth(), img.getHeight());
}
};
BitmapField field=new BitmapField(back);
field.setPadding(0, 0, 0, 0);
manager.add(field);
add(manager);
}
}
My screen shots:
By using another dummy image, it is possible to determine which pixels of the original image needs to be deleted (we can make them transparent). Though It may not be the optimal solution, but it can be applied for any geometric figure we can draw on BlackBerry.
Check following steps:
Create a new Bitmap image (dummyImage) of same dimension as the
source image (myImage).
Draw (fill) the target geometric shape on it using a defined color
(fillColor).
Now for each pixel of myImage, if the same pixel of dummyImage
contains fillColor then keep it unchanged, else make this pixel
fully transparent by assigning zero (0) to it.
Now myImage is almost ready, need to trim this image for
transparent pixel removal.
Following code will apply a circular crop on a image. (but won't trim the transparent pixels).
package mypackage;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.container.MainScreen;
class MyScreen extends MainScreen {
private Bitmap myImage = Bitmap.getBitmapResource("img/myImage.jpeg");
private BitmapField _bf;
public MyScreen() {
_bf = new BitmapField(myImage);
adjustBitmapMargin();
add(_bf);
}
private void adjustBitmapMargin() {
int x = (Display.getWidth() - myImage.getWidth()) / 2;
int y = (Display.getHeight() - myImage.getHeight()) / 2;
_bf.setMargin(y, 0, 0, x);
}
protected void makeMenu(Menu menu, int instance) {
menu.add(miCropCircle);
super.makeMenu(menu, instance);
}
private MenuItem miCropCircle = new MenuItem("Crop - Circle", 0, 0) {
public void run() {
cropImage();
}
};
private void cropImage() {
int width = myImage.getWidth();
int height = myImage.getHeight();
// get original data from the image
int myImageData[] = new int[width * height];
myImage.getARGB(myImageData, 0, width, 0, 0, width, height);
// get default color of a newly created bitmap
int defaultColors[] = new int[1 * 1];
(new Bitmap(1, 1)).getARGB(defaultColors, 0, 1, 0, 0, 1, 1);
int defaultColor = defaultColors[0];
int fillColor = Color.RED;
int diameter = 200;
// dummy data preparation
Bitmap dummyImage = new Bitmap(width, height);
Graphics dummyImageGraphics = Graphics.create(dummyImage);
dummyImageGraphics.setColor(fillColor);
int startX = width / 2 - diameter / 2;
int startY = height / 2 - diameter / 2;
dummyImageGraphics.fillArc(startX, startY, diameter, diameter, 0, 360);
int dummyData[] = new int[width * height];
dummyImage.getARGB(dummyData, 0, width, 0, 0, width, height);
// filling original data with transparent value.
int totalPixels = width * height;
for (int i = 0; i < totalPixels; i++) {
if (dummyData[i] == defaultColor) {
myImageData[i] = 0;
}
}
// set new data
myImage.setARGB(myImageData, 0, width, 0, 0, width, height);
// redraw screen
_bf.setBitmap(myImage);
adjustBitmapMargin();
invalidate();
// free up some memory here
defaultColors = null;
dummyImage = null;
dummyData = null;
dummyImageGraphics = null;
}
}
Output of the above code:
I'm creating a simple blackberry application for testing purposes and my custom buttons do not show on the UI of the simulator.
I've created a custom button called CustomButtonField and here is the code:
package test.expense;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
public class CustomButtonField extends Field {
String label;
int backgroundColor;
int foregroundColor;
public CustomButtonField(String label, int backgroundColor, int foregroundColor, long style){
super(style);
this.label = label;
this.backgroundColor = backgroundColor;
this.foregroundColor = foregroundColor;
}
public int getPreferedHeight(){
return getFont().getHeight() + 8;
}
public int getPreferedWidth(){
return getFont().getAdvance(label) + 8;
}
protected void layout(int width, int height) {
setExtent(Math.min(width, getPreferredWidth()), Math.min(height, getPreferredHeight()));
}
protected void paint(Graphics graphics) {
graphics.setColor(backgroundColor);
graphics.fillRoundRect(1, 1, getWidth()-2, getHeight()-2, 12, 12);
graphics.setColor(foregroundColor);
graphics.drawText(label, 4, 4);
}
}
And here is where I invoke it and display it:
HorizontalFieldManager buttonManager = new HorizontalFieldManager(FIELD_RIGHT);
CustomButtonField btnCancel;
CustomButtonField btnSubmit;
public ExpenseSheetScreen() {
super();
btnCancel = new CustomButtonField("Cancel", Color.WHITE, 0x716eb3, 0);
btnCancel.setChangeListener(this);
btnSubmit = new CustomButtonField("Submit", Color.WHITE, 0x716eb3, 0);
btnSubmit.setChangeListener(this);
buttonManager.add(btnCancel);
buttonManager.add(btnSubmit);
add(buttonManager);
}// End Expense Sheet Screen.
What am I doing wrong?
protected void layout(int width, int height) {
setExtent(Math.min(width, getPreferredWidth()),
Math.min(height, getPreferredHeight()));
}
setExtend is set to 0, 0 all the time.
I'm having an interesting anomaly when displaying a listfield on the blackberry simulator:
The top item is the height of a single line of text (about 12 pixels) while the rest are fine.
Does anyone know why only the top item is being drawn this way? Also, when I add an empty venue in position 0, it still displays the first actual venue this way (item in position 1).
Not sure what to do.
Thanks for any help.
The layout looks like this:
-----------------------------------
| *part of image* | title |
-----------------------------------
| | title |
| * full image * | address |
| | city, zip |
-----------------------------------
The object is called like so:
listField = new ListField( venueList.size() );
listField.setCallback( this );
listField.setSelectedIndex(-1);
_middle.add( listField );
Here is the drawListRow code:
public void drawListRow( ListField listField, Graphics graphics,
int index, int y, int width )
{
listField.setRowHeight(90);
Hashtable item = (Hashtable) venueList.elementAt( index );
String venue_name = (String) item.get("name");
String image_url = (String) item.get("image_url");
String address = (String) item.get("address");
String city = (String) item.get("city");
String zip = (String) item.get("zip");
EncodedImage img = null;
try
{
String filename = image_url.substring(image_url.indexOf("crop/")
+ 5, image_url.length() );
FileConnection fconn = (FileConnection)Connector.open(
"file:///SDCard/Blackberry/project1/" + filename,
Connector.READ);
if ( !fconn.exists() )
{
}
else
{
InputStream input = fconn.openInputStream();
byte[] data = new byte[(int)fconn.fileSize()];
input.read(data);
input.close();
if(data.length > 0)
{
EncodedImage rawimg = EncodedImage.createEncodedImage(
data, 0, data.length);
int dw = Fixed32.toFP(Display.getWidth());
int iw = Fixed32.toFP(rawimg.getWidth());
int sf = Fixed32.div(iw, dw);
img = rawimg.scaleImage32(sf * 4, sf * 4);
}
else
{
}
}
}
catch(IOException ef)
{
}
graphics.drawText( venue_name, 140, y, 0, width );
graphics.drawText( address, 140, y + 15, 0, width );
graphics.drawText( city + ", " + zip, 140, y + 30, 0, width );
if(img != null)
{
graphics.drawImage(0, y, img.getWidth(), img.getHeight(),
img, 0, 0, 0);
}
}
setRowHeight should be called once after construction of ListField, not inside of drawListRow on each time row is repainted:
listField = new ListField( venueList.size() );
listField.setRowHeight(90);
listField.setCallback( this );
listField.setSelectedIndex(-1);
_middle.add( listField );
Aman,
Hopefully you can use this for something. You should be able to extract the list field data from this wildly out of control class. Remember, this is a work in progress, so you will have to strip out the things that are quite clearly custom to my app. Like the image handling that relies on a substring for a file name.
It works fine for me, but it will totally not work for anyone htat just copies and pastes, so good luck...
package venue;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import net.rim.device.api.math.Fixed32;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.FocusChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
public class categoryView extends MainScreen implements FieldChangeListener, ListFieldCallback, FocusChangeListener {
private HorizontalFieldManager _top;
private HorizontalFieldManager _nav;
private VerticalFieldManager _middle;
private int horizontalOffset;
private final static long animationTime = 300;
private long animationStart = 0;
private int venue_id;
private int category_id;
private CustomButtonField rectangle;
private Vector venueList = new Vector();
private Hashtable venue_index = new Hashtable();
private Vector image_index = new Vector();
private ListField listField;
private int last_menu_item = 2;
private int last_nav = 2;
private int before_last = 1;
private int location_count = 0;
private int img_width = 120;
private int img_height = 80;
private Field f;
public categoryView(int id) {
super();
category_id = id;
horizontalOffset = Display.getWidth();
_top = new HorizontalFieldManager(Manager.USE_ALL_WIDTH | Field.FIELD_HCENTER)
{
public void paint(Graphics gr)
{
Bitmap bg = Bitmap.getBitmapResource("bg.png");
gr.drawBitmap(0, 0, Display.getWidth(), Display.getHeight(), bg, 0, 0);
subpaint(gr);
}
};
_nav = new HorizontalFieldManager(Field.USE_ALL_WIDTH);
_middle = new VerticalFieldManager();
add(_top);
add(_nav);
add(_middle);
Bitmap lol = Bitmap.getBitmapResource("logo.png");
BitmapField lolfield = new BitmapField(lol);
_top.add(lolfield);
HorizontalFieldManager nav = new HorizontalFieldManager(Field.USE_ALL_WIDTH | Manager.HORIZONTAL_SCROLL);
Vector locs = getLocations();
Hashtable locations = (Hashtable) locs.elementAt(0);
Enumeration ne = locations.keys();
Enumeration nv = locations.elements();
int counter = 1;
if(locations.size() > 1)
{
counter = locations.size() - 1;
}
int count = 1;
while(ne.hasMoreElements())
{
final String location_id = ne.nextElement().toString();
String location = nv.nextElement().toString();
last_nav = Integer.parseInt(location_id);
rectangle = new CustomButtonField(location_id, location, 25, Field.FOCUSABLE);
rectangle.setFocusListener(this);
nav.add(rectangle);
if(count == counter)
{
before_last = Integer.parseInt(location_id);
}
count ++;
}
_nav.add(nav);
}
public void setDefaultLocation()
{
Vector locs = getLocations();
Hashtable loc1 = (Hashtable) locs.elementAt(0);
Enumeration er = loc1.keys();
Enumeration vr = loc1.elements();
int i = 0;
while(er.hasMoreElements())
{
final String location_id = er.nextElement().toString();
if(i == 0)
{
last_menu_item = Integer.parseInt(location_id);
}
i ++;
}
}
public void drawMiddle()
{
Vector venues = getVenues(category_id);
Hashtable venue_list = (Hashtable) venues.elementAt(0);
Enumeration e = venue_list.keys();
Enumeration v = venue_list.elements();
int count = 0;
while(e.hasMoreElements())
{
String vid = e.nextElement().toString();
Hashtable elm = (Hashtable)v.nextElement();
venueList.addElement(elm);
venue_index.put(Integer.toString(count), (String) elm.get("venue_id"));
EncodedImage img = null;
String image_url = (String) elm.get("image_url");
try
{
String filename;
if(image_url.length() > 5)
{
filename = image_url.substring( image_url.indexOf("crop/") + 5, image_url.length() );
}
else
{
filename = "1.png";
}
FileConnection fconn = (FileConnection) Connector.open( "file:///SDCard/Blackberry/venue/" + filename, Connector.READ);
if ( !fconn.exists() )
{
}
else
{
InputStream input = fconn.openInputStream();
byte[] data = new byte[(int)fconn.fileSize()];
input.read(data);
input.close();
if(data.length > 0)
{
EncodedImage rawimg = EncodedImage.createEncodedImage(data, 0, data.length);
int dw = Fixed32.toFP(Display.getWidth());
int iw = Fixed32.toFP(rawimg.getWidth());
int sf = Fixed32.div(iw, dw);
img = rawimg.scaleImage32(sf * 4, sf * 4);
img_width = (int) Math.ceil(Display.getWidth() / 4);
img_height = (int) Math.ceil(Display.getWidth() / 6);
}
else
{
}
}
}
catch(IOException ef)
{
}
image_index.addElement(img);
count ++;
}
final int count_results = count;
_middle = new VerticalFieldManager( Manager.VERTICAL_SCROLLBAR )
{
public void paint(Graphics graphics)
{
graphics.setBackgroundColor(0xFFFFFF);
graphics.setColor(Color.BLACK);
graphics.clear();
super.paint(graphics);
}
protected void sublayout(int maxWidth, int maxHeight)
{
int displayWidth = Display.getWidth();
//int displayHeight = Display.getHeight();
int displayHeight = count_results * img_height;
super.sublayout( displayWidth, displayHeight);
setExtent( displayWidth, displayHeight);
}
};
add(_middle);
listField = new ListField( venueList.size() );
listField.setCallback( this );
listField.setSelectedIndex(-1);
listField.setRowHeight(img_height);
_middle.add( listField );
_middle.add(new RichTextField(Field.NON_FOCUSABLE));
}
public boolean navigationClick(int status, int time) {
Field focus = UiApplication.getUiApplication().getActiveScreen() .getLeafFieldWithFocus();
if (focus instanceof ListField) {
int selected = listField.getSelectedIndex();
String venue_id = (String) venue_index.get(Integer.toString(selected));
moveScreens(venue_id);
}
return true;
}
void setListSize()
{
listField.setSize( venueList.size() );
}
public void drawListRow( ListField listField, Graphics graphics, int index, int y, int width )
{
Hashtable item = (Hashtable) venueList.elementAt( index );
String venue_name = (String) item.get("name");
String address = (String) item.get("address");
String city = (String) item.get("city");
String zip = (String) item.get("zip");
EncodedImage img = (EncodedImage) image_index.elementAt(index);
graphics.drawText( venue_name, img_width + 10, y, 0, width );
graphics.drawText( address, img_width + 10, y + 15, 0, width );
graphics.drawText( city + ", " + zip, img_width + 10, y + 30, 0, width );
if(img != null)
{
graphics.drawImage(0, y + 3, img.getWidth(), img.getHeight(), img, 0, 0, 0);
}
}
public Object get( ListField listField, int index )
{
return venueList.elementAt( index );
}
public Vector getCategories()
{
Vector results = new Vector();
database db = new database();
Vector categories = db.getCategories();
if(categories.size() > 0)
results = categories;
return results;
}
public Vector getLocations()
{
Vector results = new Vector();
database db = new database();
Vector subcats = db.getCategoryLocations(category_id);
Hashtable subs = (Hashtable) subcats.elementAt(0);
if(subs.size() > 0)
{
location_count = subs.size();
results = subcats;
}
return results;
}
public Vector getVenues(int category_id)
{
Vector results = new Vector();
database db = new database();
Vector venues = db.getLocationVenues(category_id, last_menu_item);
if(venues.size() > 0)
results = venues;
return results;
}
protected void makeMenu(Menu menu, int instance)
{
super.makeMenu(menu, instance);
menu.add(new MenuItem("Home", 10, 20){
public void run()
{
moveScreens("main");
}
});
menu.add(new MenuItem("Search", 10, 20){
public void run()
{
Dialog.inform("Search was clicked.");
}
});
Vector locs = getLocations();
Hashtable locations = (Hashtable) locs.elementAt(0);
Enumeration e = locations.keys();
Enumeration v = locations.elements();
while(e.hasMoreElements())
{
final String location_id = e.nextElement().toString();
String location = v.nextElement().toString();
menu.add(new MenuItem(location, 10, 20){
public void run()
{
Dialog.inform("Location " + location_id + " was clicked");
}
});
}
}
public void moveScreens(String type)
{
if(type == "main")
{
UiApplication.getUiApplication().popScreen(this);
}
else
{
int venue_id = Integer.parseInt(type);
Screen newScreen = new ViewVenue(venue_id);
UiApplication.getUiApplication().pushScreen(newScreen);
}
}
protected void sublayout(int width, int height)
{
super.sublayout(width, height);
if(horizontalOffset > 0)
{
if(animationStart == 0)
{
animationStart = System.currentTimeMillis();
}
else
{
long timeElapsed = System.currentTimeMillis() - animationStart;
if(timeElapsed >= animationTime)
{
horizontalOffset = 0;
}
else
{
float percentDone = (float)timeElapsed / (float)animationTime;
horizontalOffset = Display.getWidth() - (int)(percentDone * Display.getWidth());
}
}
}
setPosition(horizontalOffset, 0);
if(horizontalOffset > 0)
{
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run()
{
updateLayout();
}
});
}
}
public void fieldChanged(Field field, int context)
{
int id = 0;
if (field instanceof CustomButtonField) {
id = ((CustomButtonField)field).getId();
}
venue_id = id;
Dialog.inform(Integer.toString(venue_id));
//moveScreens("venue");
}
public void focusChanged(Field field, int eventType) {
if((eventType == FocusChangeListener.FOCUS_GAINED)) {
if (field instanceof CustomButtonField) {
final int id = ((CustomButtonField)field).getId();
if(id == last_nav && before_last != last_menu_item && last_nav != before_last)
{
//updateContent(id);
f.setFocus();
}
else
{
updateContent(id);
f = field;
}
}
}
}
public void updateContent(final int id)
{
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run()
{
delete(_middle);
venueList.removeAllElements();
image_index.removeAllElements();
last_menu_item = id;
drawMiddle();
}
});
}
public boolean onSavePrompt()
{
// do nothing
return true;
}
public int getPreferredWidth(ListField listField) {
// TODO Auto-generated method stub
return 0;
}
public int indexOfList(ListField listField, String prefix, int start) {
// TODO Auto-generated method stub
return 0;
}
}
It's easy to show some animation within one field - BitmapField or Screen:
[Blackberry - background image/animation RIM OS 4.5.0][1]
But what if you need to move fields, not just images?
May be used:
game workflow functionality, like chess, puzzle etc
application user-defined layout, like in Google gadgets
enhanced GUI animation effects
So, I'd like to exchange my expirience in this task, on the other hand, I'd like to know about any others possibilities and suggestions.
This effect may be easily achived with custom layout:
class AnimatedManager extends Manager {
int ANIMATION_NONE = 0;
int ANIMATION_CROSS_FLY = 1;
boolean mAnimationStart = false;
Bitmap mBmpBNormal = Bitmap.getBitmapResource("blue_normal.png");
Bitmap mBmpBFocused = Bitmap.getBitmapResource("blue_focused.png");
Bitmap mBmpRNormal = Bitmap.getBitmapResource("red_normal.png");
Bitmap mBmpRFocused = Bitmap.getBitmapResource("red_focused.png");
Bitmap mBmpYNormal = Bitmap.getBitmapResource("yellow_normal.png");
Bitmap mBmpYFocused = Bitmap.getBitmapResource("yellow_focused.png");
Bitmap mBmpGNormal = Bitmap.getBitmapResource("green_normal.png");
Bitmap mBmpGFocused = Bitmap.getBitmapResource("green_focused.png");
int[] width = null;
int[] height = null;
int[] xPos = null;
int[] yPos = null;
BitmapButtonField mBButton = new BitmapButtonField(mBmpBNormal,
mBmpBFocused);
BitmapButtonField mRButton = new BitmapButtonField(mBmpRNormal,
mBmpRFocused);
BitmapButtonField mYButton = new BitmapButtonField(mBmpYNormal,
mBmpYFocused);
BitmapButtonField mGButton = new BitmapButtonField(mBmpGNormal,
mBmpGFocused);
public AnimatedManager() {
super(USE_ALL_HEIGHT | USE_ALL_WIDTH);
add(mBButton);
add(mRButton);
add(mYButton);
add(mGButton);
width = new int[] { mBButton.getPreferredWidth(),
mRButton.getPreferredWidth(),
mYButton.getPreferredWidth(),
mGButton.getPreferredWidth() };
height = new int[] { mBButton.getPreferredHeight(),
mRButton.getPreferredHeight(),
mYButton.getPreferredHeight(),
mGButton.getPreferredHeight() };
xPos = new int[] { 0, getPreferredWidth() - width[1], 0,
getPreferredWidth() - width[3] };
yPos = new int[] { 0, 0, getPreferredHeight() - height[2],
getPreferredHeight() - height[3] };
Timer timer = new Timer();
timer.schedule(mAnimationTask, 0, 100);
}
TimerTask mAnimationTask = new TimerTask() {
public void run() {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
updateLayout();
};
});
};
};
MenuItem mAnimationMenuItem = new MenuItem("Start", 0, 0) {
public void run() {
mAnimationStart = true;
};
};
protected void makeMenu(Menu menu, int instance) {
super.makeMenu(menu, instance);
menu.add(mAnimationMenuItem);
}
public int getPreferredHeight() {
return Display.getHeight();
}
public int getPreferredWidth() {
return Display.getWidth();
}
protected void sublayout(int width, int height) {
width = getPreferredWidth();
height = getPreferredHeight();
if (getFieldCount() > 3) {
Field first = getField(0);
Field second = getField(1);
Field third = getField(2);
Field fourth = getField(3);
layoutChild(first, this.width[0], this.height[0]);
layoutChild(second, this.width[1], this.height[1]);
layoutChild(third, this.width[2], this.height[2]);
layoutChild(fourth, this.width[3], this.height[3]);
if (mAnimationStart) {
boolean anim1 = performLayoutAnimation(0,
width - this.width[0],
height - this.height[0]);
boolean anim2 = performLayoutAnimation(1, 0,
height - this.height[1]);
boolean anim3 = performLayoutAnimation(2,
width - this.width[2], 0);
boolean anim4 = performLayoutAnimation(3, 0, 0);
mAnimationStart = anim1 || anim2 || anim3 || anim4;
}
setPositionChild(first, xPos[0], yPos[0]);
setPositionChild(second, xPos[1], yPos[1]);
setPositionChild(third, xPos[2], yPos[2]);
setPositionChild(fourth, xPos[3], yPos[3]);
}
setExtent(width, height);
}
boolean performLayoutAnimation(int fieldIndex, int x, int y) {
boolean result = false;
if (xPos[fieldIndex] > x) {
xPos[fieldIndex] -= 2;
result = true;
} else if (xPos[fieldIndex] < x) {
xPos[fieldIndex] += 2;
result = true;
}
if (yPos[fieldIndex] > y) {
yPos[fieldIndex] -= 1;
result = true;
} else if (yPos[fieldIndex] < y) {
yPos[fieldIndex] += 1;
result = true;
}
return result;
}
}
BitmapButtonField class I've used:
class BitmapButtonField extends ButtonField {
Bitmap mNormal;
Bitmap mFocused;
int mWidth;
int mHeight;
public BitmapButtonField(Bitmap normal, Bitmap focused) {
super(CONSUME_CLICK);
mNormal = normal;
mFocused = focused;
mWidth = mNormal.getWidth();
mHeight = mNormal.getHeight();
setMargin(0, 0, 0, 0);
setPadding(0, 0, 0, 0);
setBorder(BorderFactory.createSimpleBorder(new XYEdges(0, 0, 0, 0)));
setBorder(VISUAL_STATE_ACTIVE, BorderFactory
.createSimpleBorder(new XYEdges(0, 0, 0, 0)));
}
protected void paint(Graphics graphics) {
Bitmap bitmap = null;
switch (getVisualState()) {
case VISUAL_STATE_NORMAL:
bitmap = mNormal;
break;
case VISUAL_STATE_FOCUS:
bitmap = mFocused;
break;
case VISUAL_STATE_ACTIVE:
bitmap = mFocused;
break;
default:
bitmap = mNormal;
}
graphics.drawBitmap(0, 0, bitmap.getWidth(), bitmap.getHeight(),
bitmap, 0, 0);
}
public int getPreferredWidth() {
return mWidth;
}
public int getPreferredHeight() {
return mHeight;
}
protected void layout(int width, int height) {
setExtent(mWidth, mHeight);
}
protected void applyTheme(Graphics arg0, boolean arg1) {
}
}
I need to display a custom icon and two hyperlinks in model pop up on Blackberry map. How can I do this?
alt text http://img689.imageshack.us/img689/2886/maplinkicon.jpg
First implement extention of ButtonField which will:
look like icon
on click will open Browser with predefined link
will use context menu
Code for such control:
class MapLinkIcon extends ButtonField implements FieldChangeListener {
Bitmap mNormal;
Bitmap mFocused;
String mLink;
String mDescription;
int mWidth;
int mHeight;
public MapLinkIcon(Bitmap normal, Bitmap focused, String link,
String description) {
super(CONSUME_CLICK);
mNormal = normal;
mFocused = focused;
mLink = link;
mDescription = description;
mWidth = mNormal.getWidth();
mHeight = mNormal.getHeight();
setMargin(0, 0, 0, 0);
setPadding(0, 0, 0, 0);
setBorder(BorderFactory.createSimpleBorder(new XYEdges(0, 0, 0, 0)));
setBorder(VISUAL_STATE_ACTIVE, BorderFactory
.createSimpleBorder(new XYEdges(0, 0, 0, 0)));
this.setChangeListener(this);
}
protected void paint(Graphics graphics) {
Bitmap bitmap = null;
switch (getVisualState()) {
case VISUAL_STATE_NORMAL:
bitmap = mNormal;
break;
case VISUAL_STATE_FOCUS:
bitmap = mFocused;
break;
case VISUAL_STATE_ACTIVE:
bitmap = mFocused;
break;
default:
bitmap = mNormal;
}
graphics.drawBitmap(0, 0, bitmap.getWidth(), bitmap.getHeight(),
bitmap, 0, 0);
}
public int getPreferredWidth() {
return mWidth;
}
public int getPreferredHeight() {
return mHeight;
}
protected void layout(int width, int height) {
setExtent(mWidth, mHeight);
}
protected void applyTheme(Graphics arg0, boolean arg1) {
}
public void fieldChanged(Field field, int context) {
openLink(mLink);
}
MenuItem mMenuItem = new MenuItem("Go To Link", 0, 0) {
public void run() {
openLink(mLink);
}
};
protected void makeContextMenu(ContextMenu contextMenu) {
super.makeContextMenu(contextMenu);
contextMenu.addItem(mMenuItem);
}
private static void openLink(String link) {
Browser.getDefaultSession().displayPage(link);
}
}
Now we can use this button control in combination with MapField, override sublayout to place button over the map:
class CustomMapField extends VerticalFieldManager {
MapField mMapField;
MapLinkIcon mButton;
public CustomMapField() {
add(mMapField = new MapField());
}
public int getPreferredHeight() {
return getScreen().getHeight();
}
public int getPreferredWidth() {
return getScreen().getWidth();
}
public void moveTo(Coordinates coordinates, Bitmap icoNorm, Bitmap icoAct,
String link, String description) {
mMapField.moveTo(coordinates);
add(mButton = new MapLinkIcon(icoNorm, icoAct, link, description));
}
protected void sublayout(int maxWidth, int maxHeight) {
int width = getPreferredWidth();
int height = getPreferredHeight();
layoutChild(mMapField, width, height);
setPositionChild(mMapField, 0, 0);
layoutChild(mButton, mButton.mWidth, mButton.mHeight);
XYPoint fieldOut = new XYPoint();
mMapField.convertWorldToField(mMapField.getCoordinates(), fieldOut);
int xPos = fieldOut.x - mButton.mWidth / 2;
int yPos = fieldOut.y - mButton.mHeight;
setPositionChild(mButton, xPos, yPos);
setExtent(width, height);
}
}
Example of use:
class Scr extends MainScreen {
CustomMapField mMapField;
Coordinates mCoordinates;
public Scr() {
double latitude = 51.507778;
double longitude = -0.128056;
mCoordinates = new Coordinates(latitude, longitude, 0);
mMapField = new CustomMapField();
Bitmap icoNormal = Bitmap.getBitmapResource("so_icon_normal.png");
Bitmap icoActive = Bitmap.getBitmapResource("so_icon_active.png");
String link = "http://stackoverflow.com";
String description = "StackOverflow";
mMapField.moveTo(mCoordinates, icoNormal, icoActive, link, description);
add(mMapField);
}
}
See also:
How to show our own icon in BlackBerry Map?
How to show more than one location in Blackberry MapField?