Blackberry - How to center the datepicker popup for DateField - blackberry

I have DateField in center of my screen
And when I touch it I see:
But I want to see:
My question is:
How can I center the datepicker popup for DateField?
Blackberry OS 6
Update:
public class MyMainScreen extends MainScreen
{
protected DateField dateField_ = null;
protected VerticalFieldManager container_ = null;
public MyMainScreen()
{
super();
container_ = new VerticalFieldManager(VerticalFieldManager.VERTICAL_SCROLL
| VerticalFieldManager.VERTICAL_SCROLLBAR | VerticalFieldManager.USE_ALL_HEIGHT)
{
protected void sublayout(int width, int height)
{
super.sublayout(width, height);
layoutChild(dateField_ , 100, 40);
setPositionChild(dateField_ , (width - 100) / 2, 50);
setVirtualExtent(width, 50);
}
};
add(container_);
dateField_ = new DateField("", new Date(), new SimpleDateFormat("HH:mm"), Field.FIELD_HCENTER |
DrawStyle.HCENTER | Field.FOCUSABLE);
container_.add(dateField_);
add(container_);
}
}

Ok, so there's a few problems:
the DateField won't center the field just because you pass Field.FIELD_HCENTER | DrawStyle.HCENTER into the constructor. I don't think DateField even recognizes those flags.
A VerticalFieldManager is a special Manager that's designed to lay out its children vertically from top-to-bottom in the order you add() them. If you're not going to lay out the fields that way, then I don't know that you should extend VerticalFieldManager. Just extend Manager directly, if you want to implement sublayout(). Also, calling super.sublayout() in your implementation might cause issues.
You are hardcoding the height/width of your DateField. I'm not sure it allows that.
Your code didn't actually compile for me, as the DateField constructor takes a long date, not a Date. That doesn't have anything to do with centering though.
So, I'd recommend something like this:
super(MainScreen.VERTICAL_SCROLL | MainScreen.VERTICAL_SCROLLBAR);
dateField_ = new DateField("", (new Date()).getTime(), new SimpleDateFormat("HH:mm"), Field.FOCUSABLE);
container_ = new Manager(Manager.VERTICAL_SCROLL | Manager.VERTICAL_SCROLLBAR) {
public int getPreferredHeight() {
return Display.getHeight();
}
public int getPreferredWidth() {
return Display.getWidth();
}
protected void sublayout(int width, int height) {
int h = Math.min(height, Display.getHeight());
setExtent(width, h);
// only needed if there's actually more content than fits in the visible area
//setVirtualExtent(width, h + ?);
int dfWidth = dateField_.getPreferredWidth();
int dfHeight = dateField_.getPreferredHeight();
layoutChild(dateField_, dfWidth, dfHeight);
setPositionChild(dateField_, (width - dfWidth) / 2, (h - dfHeight) / 2);
}
};
container_.add(dateField_);
add(container_);
P.S. I wasn't sure if you wanted scrolling or not. With only a DateField, there's no reason to scroll. But, I know your real Screen probably has more content, so you may need to setVirtualExtent(), which I've commented out.

This solution works for me also:
package com.my.package;
import java.util.Calendar;
import java.util.Date;
import net.rim.device.api.i18n.SimpleDateFormat;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.TouchEvent;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.DateField;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.picker.DateTimePicker;
public class MyDateManager extends VerticalFieldManager {
protected DateField dateField_ = null;
protected DateTimePicker dateTimePicker_ = null;
protected SimpleDateFormat dateFormat_ = null;
public MyDateManager() {
super(Manager.FIELD_HCENTER | Manager.FIELD_VCENTER);
dateFormat_ = new SimpleDateFormat("HH:mm");
dateField_ = new DateField("", new Date().getTime(), dateFormat_,
Field.FIELD_HCENTER | DrawStyle.HCENTER | Field.FOCUSABLE) {
protected boolean touchEvent(TouchEvent paramTouchEvent) {
if (paramTouchEvent.getEvent() == TouchEvent.CLICK) {
dateField_.setEnabled(false);
showDatePicker();
}
return super.touchEvent(paramTouchEvent);
}
protected boolean trackwheelClick(int paramInt1, int paramInt2) {
dateField_.setEnabled(false);
showDatePicker();
return super.trackwheelClick(paramInt1, paramInt2);
}
};
this.add(dateField_);
}
protected void sublayout(int width, int height) {
layoutChild(dateField_, width, height);
setPositionChild(dateField_, (width - dateField_.getWidth()) / 2,
(height - dateField_.getHeight()) / 2);
int h = dateField_.getHeight();
if (h <= 0)
h = height;
setExtent(width, h);
}
protected void showDatePicker() {
if (dateTimePicker_ == null) {
Calendar cal = Calendar.getInstance();
// HACK
String dateFormat = dateFormat_.toPattern().indexOf("H", 0) == -1 ? dateFormat_
.toPattern() : null;
String timeFormat = dateFormat_.toPattern().indexOf("H", 0) != -1 ? dateFormat_
.toPattern() : null;
dateTimePicker_ = DateTimePicker.createInstance(cal, dateFormat,
timeFormat);
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
if (dateTimePicker_.doModal()) {
dateField_.setDate(dateTimePicker_.getDateTime()
.getTime());
}
dateField_.setEnabled(true);
dateField_.setFocus();
dateTimePicker_ = null;
}
});
}
}
}

Related

Custom BitmapField bug on unfocus and scroll (BlackBerry)

I have been having this annoying problem when trying to implement a picture gallery on BlackBerry 6.
Everything works, however when the focus changes from the top buttons to say the pictures further down the screen, the images seem to glitch and not paint themselves correctly. Please see the images below for an example:
(Focus is on the top of the screen(not shown))
(Focus is now on the bottom left image, note that the top image is now blank for an unknown reason)
And this happens no matter how many pictures I add to the tumbnail gallery.
Now here is my code, (a part of it concerning the drawing of the thumbnails)
public ProductImage(String productName){
super(VERTICAL_SCROLL|VERTICAL_SCROLLBAR);
currentProduct = productName;
createGUI();
}
public void createGUI(){
deleteAll();
try{
Storage.loadPicture();
}catch(NullPointerException e){
e.printStackTrace();
}
this.setTitle(new LabelField(_resources.getString(PRODUCT_IMAGE), Field.FIELD_HCENTER));
if(ToolbarManager.isToolbarSupported())
{
Toolbar tb = new Toolbar();
setToolbar(tb.createToolBar());
}
else{
Toolbar tb = new Toolbar();
add(tb.createNavBar());
}
picVector = Storage.getPicture(currentProduct);
EncodedImage enc = EncodedImage.getEncodedImageResource("camera.png");
EncodedImage sizeEnc = ImageResizer.sizeImage(enc, Display.getHeight(), Display.getHeight());
takenPicture = new BitmapField(enc.getBitmap());
vfMain = new VerticalFieldManager();
vfMain.add(logo);
vfMain.add(new SeparatorField());
add(vfMain);
prepareBmpFields();
}
private void prepareBmpFields() {
System.out.println("This is the vector size: " + picVector.getPicVector().size());
LayoutManager manager = new LayoutManager();
FieldChangeListener itemListener = new ButtonListener();
mBmpFields = new ImageButtonField[picVector.getPicVector().size()];
for (int i = 0; i < picVector.getPicVector().size(); i++) {
/*EncodedImage image = EncodedImage
.getEncodedImageResource((String)imageVector.elementAt(i));*/
byte[] data = getData((String)picVector.getPicVector().elementAt(i));
//Encode and Resize image
EncodedImage eImage = EncodedImage.createEncodedImage(data,0,data.length);
eImage = ImageResizer.resizeImage(eImage, mImgWidth, mImgHeight);
ImageButtonField currentImage = new ImageButtonField(eImage.getBitmap());
currentImage.setAssociatedPath((String)picVector.getPicVector().elementAt(i));
mBmpFields[i] = currentImage;
mBmpFields[i].setChangeListener(itemListener);
manager.add(mBmpFields[i]);
}
vfMain.add(manager);
}
private class LayoutManager extends VerticalFieldManager {
public LayoutManager() {
super(VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
}
protected void sublayout(int width, int height) {
int columns = mScrWidth / (mImgWidth + 2 * mImgMargin);
int scrWidth = Display.getWidth();
int rows = mBmpFields.length / columns
+ (mBmpFields.length % columns > 0 ? 1 : 0);
int counter = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
int posX = j * (mImgWidth + 2 * mImgMargin) + mImgMargin;
int posY = i * (mImgHeight + 2 * mImgMargin) + mImgMargin;
if(mBmpFields.length > counter){
Field field = mBmpFields[counter];
layoutChild(field, mImgWidth, mImgHeight);
setPositionChild(field, posX, posY);
counter++;
};
}
}
if(Display.getWidth() < Display.getHeight()){
setExtent(mScrWidth, (int)(mScrHeight*1.25));
}
else{
setExtent(mScrWidth, (int)(mScrHeight*2));
}
}
public int getPreferredWidth() {
return mScrWidth;
}
public int getPreferredHeight() {
return mScrHeight;
}
}
}
I have removed many non relevant parts of the code, but the needed code is there.
Does anyone know what could be causing this problem? Thanks for your help!
Edit: as requested, here is my implementation of ImageButtonField class:
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.BitmapField;
public class ImageButtonField extends BitmapField{
String associatedPath ="";
BitmapField image2;
public ImageButtonField(Bitmap image) {
super(image);
}
public void setAssociatedPath(String path){
associatedPath = path;
}
public String getAssociatedPath(){
return associatedPath;
}
public boolean isFocusable() {
return true;
}
protected void applyTheme(Graphics arg0, boolean arg1) {
}
protected void drawFocus(Graphics graphics, boolean on) {
}
protected void onFocus(int direction) {
// only change appearance if this button is enabled (aka editable)
if (isEditable()) {
invalidate(); // repaint
}
super.onFocus(direction);
}
public void onUnfocus() {
invalidate(); // repaint
super.onUnfocus();
}
protected boolean navigationClick(int status, int time) {
fieldChangeNotify(0);
return true;
}
protected boolean trackwheelClick(int status, int time) {
fieldChangeNotify(0);
return true;
}
protected void paint(Graphics graphics) {
super.paint(graphics);
if (isFocus()) {
graphics.setGlobalAlpha(128);
graphics.setColor(0x888888);
graphics.fillRect(0, 0, getWidth(), getHeight());
}else{
graphics.setGlobalAlpha(0);
graphics.setColor(0x000000);
graphics.fillRect(0, 0, getWidth(), getHeight());
//graphics.drawBitmap(0, 0, getWidth(), getHeight(), image2.getB, 0, 0);
}
}
protected boolean keyChar(char character, int status, int time) {
if(Characters.ENTER == character || Characters.SPACE == character) {
fieldChangeNotify(0);
return true;
}
return super.keyChar(character, status, time);
}
}
Ok, so you can disregard my first answer, but since I didn't have your ImageButtonField code at the time, I don't want to throw it out ... maybe someone else will find it useful.
In the end, I didn't need to make any changes to ImageButtonField, but I did change your LayoutManager class. The way I figured out that it was the problem was I just started replacing your custom UI classes with built-in ones. I replaced ImageButtonField with BitmapField. That didn't fix it. Then, I replaced LayoutManager with FlowFieldManager and that fixed it. So, I knew where the problem was.
My solution:
private class LayoutManager extends Manager {
public LayoutManager() {
super(VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
}
protected void sublayout(int width, int height) {
setExtent(width, height);
// TODO: maybe always set the same virtual extent?
if (Display.getWidth() < Display.getHeight()) {
setVirtualExtent(mScrWidth, (int) (mScrHeight * 1.25));
} else {
setVirtualExtent(mScrWidth, (int) (mScrHeight * 2));
}
int columns = mScrWidth / (mImgWidth + 2 * mImgMargin);
// int scrWidth = Display.getWidth();
int rows = mBmpFields.length / columns + (mBmpFields.length % columns > 0 ? 1 : 0);
int counter = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
int posX = j * (mImgWidth + 2 * mImgMargin) + mImgMargin;
int posY = i * (mImgHeight + 2 * mImgMargin) + mImgMargin;
if (mBmpFields.length > counter) {
Field field = mBmpFields[counter];
layoutChild(field, mImgWidth, mImgHeight);
setPositionChild(field, posX, posY);
counter++;
}
}
}
}
public int getPreferredWidth() {
return mScrWidth;
}
public int getPreferredHeight() {
return mScrHeight;
}
}
I can't say for sure that I understand why your original code wasn't working, but I can say that I wouldn't have done a few of the things in the original code:
The original code was extending VerticalFieldManager but was doing all the work itself, in sublayout(). So, I don't think there was any point extending VerticalFieldManager. I changed it to just extend Manager.
The original code was calling setExtent() with different sizes. I don't think that's what you wanted. Extent is the actual size of the Field. Virtual extent is the virtual size, which is what you want to set larger than the actual extent, in order to enable scrolling. You don't need to dynamically calculate different extents for portrait vs. landscape because the width and height parameters passed to sublayout() will already reflect that. I'm not sure you really even need to be setting different virtual extents either. I think you should probably always set the virtual extent height to the number of rows times picture height, accounting for margins.
You had an unused variable scrWidth in your original code. I commented it out above.
You also posted this question recently, right? Am I correct in assuming that the ImageButtonField you refer to here is the same one you were working on in the other question?
I can't see your full implementation of ImageButtonField, which you should probably post here, too. However, looking at the answers to your other question, I have a feeling that you're doing some custom focus handling in ImageButtonField, and maybe it's not being done quite right. In any case, that class may be where the problem is.
I have a similar Field subclass of my own, and here are the focus handling methods I define:
public class CustomButtonField extends Field {
private Bitmap _button; // the currently displayed button image
private Bitmap _on; // image for 'on' state (aka in-focus)
private Bitmap _off; // image for 'off' state (aka out-of-focus)
protected void onFocus(int direction) {
// only change appearance if this button is enabled (aka editable)
if (isEditable()) {
_button = _on;
invalidate(); // repaint
}
super.onFocus(direction);
}
protected void onUnfocus() {
_button = _off;
invalidate(); // repaint
super.onUnfocus();
}
protected void drawFocus(Graphics graphics, boolean on) {
// override superclass implementation and do nothing
}
public boolean isFocusable() {
return true;
}
I also have a custom implementation of paint(). I won't show it all here, because a lot of the code probably has nothing to do with your problem, but my paint() does include this call:
graphics.drawBitmap(_padding, _padding, _fieldWidth, _fieldHeight, _button, 0, 0);
You might not care about the fact that I have separate images for focused, and unfocused states ... maybe you show the same image at all times.
But, probably the thing to check is your onFocus() and onUnfocus() methods. You may need to add a call to invalidate() as I have.
Looking at Rupak's answer to your other question, it would also be good to check your ImageButtonField.paint() method, and make sure you aren't neglecting to do important drawing steps if the field is not in focus.

Editfield scroll fails to reach top in blackberry

I am having 2 EditFields in my login form with names Email: and Password:. Just below email I have login button. Suppose I come down till login, I can scroll back only till password field.The cursor fails to reach Email field. In simulator, I tried using arrow keys as well as trackpad. Please help how to scroll back to first editfield
AbsoluteFieldManager ab = new AbsoluteFieldManager();
add(ab);
new SeparatorField();
et=new EditField("Email-id:","");
pwd=new PasswordEditField("Password:","");
ab.add(et,35,110);
ab.add(pwd,35,150);
I am using AbsoluteFieldManager and developing for OS 6.0. I want the loginscreen to look like facebook login page.
Kindly let me know what can possibly be the reason for not able to scroll up
Maybe it is a RIM bug with the AbsoluteFieldManager. Never used it before so I don't know about it. You can create a work around to solve this problem. Find it below:
et=new EditField("Email-id:","");
pwd=new PasswordEditField("Password:","") {
protected int moveFocus(int amount, int status, int time) {
int cursorPosition = this.getCursorPosition();
if ((cursorPosition == 0) && (amount < 0)) {
et.setFocus();
return 0;
}
else {
return super.moveFocus(amount, status, time);
}
}
};
In this way, when you arrive to the first element in the password edit field, you will oblige the email field to get focused. This will work for you as a work around.
Another way to solve the problem is to add the two fields in an horizontal field manager, in that way I guess this will work for you for sure. If not use the first method. You can find below the code for HorizontalFieldManager:
et=new EditField("Email-id:","");
pwd=new PasswordEditField("Password:","");
HorizontalFieldManager manager = new HorizontalFieldManager();
manager.add(et);
manager.add(pwd);
ab.add(manager, yourX, yourY);
It also may be a RIM bug. What OS do you use? Is it OS 5+? Do you use custom paddings/margins/borders for some of the UI elements on the screen (including the screen itself)? If yes, try to comment out any code that sets paddings/margins/borders to check whether this it the case.
You can use this code for your login page:
public class loginscreen extends MainScreen implements FieldChangeListener {
private int deviceWidth = Display.getWidth();
private int deviceHeight = Display.getHeight();
private VerticalFieldManager subManager;
private VerticalFieldManager mainManager;
public long mycolor = 0x00FFFFFF;
Screen _screen = home.Screen;
TextField heading = new TextField(Field.NON_FOCUSABLE);
TextField username_ef = new TextField();
PasswordEditField password_ef = new PasswordEditField();
CheckboxField rememberpass = new CheckboxField();
public ButtonField login_bt = new ButtonField("Login", ButtonField.CONSUME_CLICK);
public ButtonField register_bt = new ButtonField("Register", ButtonField.CONSUME_CLICK);
public loginscreen()
{
super();
final Bitmap backgroundBitmap = Bitmap.getBitmapResource("bgd.png");
HorizontalFieldManager hfm = new HorizontalFieldManager(Manager.NO_VERTICAL_SCROLL | Manager.NO_VERTICAL_SCROLLBAR )
{
protected void sublayout(int width, int height)
{
Field field;
int numberOfFields = getFieldCount();
int x = 245;
int y = 0;
for (int i = 0;i < numberOfFields;i++)
{
field = getField(i);
setPositionChild(field,x,y);
layoutChild(field, width, height);
x +=_screen.getWidth()-381;
y += 0;//l17
}
width=_screen.getWidth();
height=48;//w19
setExtent(width, height);
}
};
mainManager = new VerticalFieldManager(Manager.NO_VERTICAL_SCROLL | Manager.NO_VERTICAL_SCROLLBAR )
{
public void paint(Graphics graphics)
{
graphics.clear();
graphics.drawBitmap(0, 0, deviceWidth, deviceHeight, backgroundBitmap, 0, 0);
super.paint(graphics);
}
};
//this manger is used for adding the componentes
subManager = new VerticalFieldManager(Manager.VERTICAL_SCROLL | Manager.VERTICAL_SCROLLBAR )
{
protected void sublayout( int maxWidth, int maxHeight )
{
int displayWidth = deviceWidth;
int displayHeight = deviceHeight;
super.sublayout( displayWidth, displayHeight);
setExtent( displayWidth, displayHeight);
}
public void paint(Graphics graphics)
{
graphics.setColor((int) mycolor);
super.paint(graphics);
}
};
username_ef.setLabel("Username: ");
password_ef.setLabel("Password: ");
rememberpass.setLabel("Remember Password");
heading.setLabel("Please enter your credentials: ");
username_ef.setMaxSize(8);
password_ef.setMaxSize(20);
subManager.add(heading);
subManager.add(username_ef);
subManager.add(password_ef);
subManager.add(rememberpass);
subManager.add(new SeparatorField());
login_bt.setChangeListener(this);
register_bt.setChangeListener(this);
hfm.add(login_bt);
hfm.add(register_bt);
subManager.add(hfm);
mainManager.add(subManager);
this.add(mainManager);
}
public boolean onSavePrompt()
{
return true;
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
if(field == login_bt)
{
//do your code for login button click
}
if(field == register_bt)
{
//code for register button click
}
}}
What you have described is not normal behavior.
My conclusion is that your code has one or more bugs, in order to solve your problem you should modify your code to fix the bugs. You will then be able to scroll up and down through the various fields.
note: As this question stands it's not possible for me to be more specific about the exact bugs. So instead I will show you an example of the layout you described that would scroll properly and you can use as a default to determine which of your deviations have caused your bugs.
// inside MainScreen constructor
add(new EditField("Username:","",0));
add(new EditField("Password:","",0));
add(new ButtonField(buttonBMP,ButtonField.CONSUME_CLICK));

Custom editfield not displaying all typed text

Below class is a textbox field. Can this be modified so that when the textbox is filled with text and user keeps type the text then scrolls ? Whats happening now is that once the textbox is filled with text any subsequent text that is typed is not being displayed.
Thanks
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.EditField;
public class CustomEditField extends EditField {
// private members of the CustomEditField class
private Font defaultFont;
// used to get the default font
private String text;
// used to specify the default width of the table cells
// constructor calls the super class constructor
public CustomEditField(String label, String initialValue, int maxNumChars,
long style) {
super(label, initialValue, maxNumChars, style);
}
// overrides the default getPreferredWidth functionality to return a fixed
// width
public int getPreferredWidth() {
defaultFont = Font.getDefault();
text = "0000000000";
return defaultFont.getAdvance(text);
}
// overrides the default layout functionality to set the width of the table
// cell
protected void layout(int width, int height) {
width = getPreferredWidth();
height = super.getPreferredHeight();
super.layout(width, height);
// uses the super class' layout functionality
// after the width and the height are set
super.setExtent(width, height);
// uses the super class' setExtent functionality
// after the width and the height are set
}
public void paint(Graphics graphics){
graphics.setBackgroundColor(Color.LIGHTBLUE);
super.paint(graphics);
}
}
This will help you to get started. It is a simplified version of the ScrollableEditField that I am using. I coded it before touch BlackBerry devices became available, therefore some additional work is required here to support TouchEvents.
class ScrollableEditField extends Manager {
private final static int DEFAULT_TOP_PADDING = 1;
private final static int DEFAULT_BOTTOM_PADDING = 1;
private final static int DEFAULT_LEFT_PADDING = 1;
private final static int DEFAULT_RIGHT_PADDING = 1;
private int TOTAL_VERTICAL_PADDING = DEFAULT_TOP_PADDING + DEFAULT_BOTTOM_PADDING;
private int TOTAL_HORIZONTAL_PADDDING = DEFAULT_LEFT_PADDING + DEFAULT_RIGHT_PADDING;
private int width = -1;
private int height = -1;
private HorizontalFieldManager hfm = new HorizontalFieldManager(HORIZONTAL_SCROLL);
private EditField ef;
public ScrollableEditField(String label, String initialValue, int maxNumChars, long innerEditFieldStyle) {
super(NO_HORIZONTAL_SCROLL);
ef = new EditField(label, initialValue, maxNumChars, innerEditFieldStyle);
hfm.add(ef);
add(hfm);
}
protected void sublayout(int width, int height) {
if (this.width != -1) {
width = this.width;
}
if (this.height != -1) {
height = this.height;
} else {
height = ef.getFont().getHeight();
}
layoutChild(hfm, width-TOTAL_HORIZONTAL_PADDDING, height-TOTAL_VERTICAL_PADDING);
setPositionChild(hfm, DEFAULT_LEFT_PADDING, DEFAULT_TOP_PADDING);
setExtent(width, height);
}
public EditField getEditField() {
return ef;
}
public void setWidth(int width) {
this.width = width;
}
protected void onFocus(int direction) {
super.onFocus(direction);
ef.setCursorPosition(0);
}
protected void onUnfocus() {
hfm.setHorizontalScroll(0);
super.onUnfocus();
}
};
public class ScrollableEditFieldScreen extends MainScreen {
public ScrollableEditFieldScreen() {
super(NO_VERTICAL_SCROLL);
setTitle("ScrollableEditField");
// hfm1 and hfm2 are here just to position the ScrollableEditField in the center of the screen
HorizontalFieldManager hfm1 = new HorizontalFieldManager(USE_ALL_HEIGHT | FIELD_HCENTER);
HorizontalFieldManager hfm2 = new HorizontalFieldManager(FIELD_VCENTER);
// instantiating the scrollable edit field and adding border
ScrollableEditField sef = new ScrollableEditField("", "", 50, 0);
sef.setBorder(BorderFactory.createRoundedBorder(new XYEdges(5,5,5,5)));
sef.setWidth(sef.getFont().getAdvance('0')*10);
hfm2.add(sef);
hfm1.add(hfm2);
add(hfm1);
}
}

Vertical scrollbar with jump points - setVerticalScroll locking UI

I have a question about the BlackBerry VerticalScrollField and scrolling which seems to lock or make the UI unstable. The following code is a BlackBerry screen with worlds as content on the left (in a scroll field) and a jumpbar off to the right that allows clicking into the content.
When a jump letter is clicked the setVerticalScroll method is called, it performs the scroll but has the unfortunate side effect of rendering the UI unstable or unusable. The scroll call is done on the UI thread so its not clear what the source of the error is. The app is being tested in a 6.0 simulator.
I've included the class which can be copied into BB Eclipse for hacking/testing.
The section that kicks of the scrolling can be found towards the bottom with the following code:
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run() {
scroller.setVerticalScroll(y, true);
}});
Here's the full class:
package test;
import java.util.Vector;
import net.rim.device.api.system.ApplicationManager;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.TouchEvent;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Status;
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 Startup extends UiApplication {
private int[] jump;
static final String[] words = new String[]{
"auto", "apple", "bear", "car", "farm", "ferret", "gold",
"green", "garden", "hedge", "happy", "igloo", "infrared",
"jelly", "kangaroo", "lemon", "lion", "marble", "moon",
"nine", "opera", "orange", "people", "puppy", "pear",
"quince", "race", "run", "sunset", "token", "willow", "zebra"
};
private final static String[] alphabet = new String[]{"A","B","C","D","E",
"F","G","H","I","J","K","L","M","N","O","P","Q","R",
"S","T","U","V","W","X","Y","Z","#"};
private VerticalFieldManager scroller;
public Startup() {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
UiApplication.getUiApplication().pushScreen(new ScrollScreen());
}
});
}
public static void main(String[] args) {
ApplicationManager app = ApplicationManager.getApplicationManager();
while (app.inStartup()) {
try { Thread.sleep(200); } catch (Throwable e) {}
}
Startup startup = new Startup();
startup.enterEventDispatcher();
}
/**
* Screen with content in a scrollbar left and a letters on the right that
* can be used to jump into the content.
*/
class ScrollScreen extends MainScreen {
public ScrollScreen() {
super(NO_HORIZONTAL_SCROLL | NO_VERTICAL_SCROLL);
HorizontalFieldManager hfm = new HorizontalFieldManager(USE_ALL_HEIGHT | NO_VERTICAL_SCROLL | NO_HORIZONTAL_SCROLL){
protected void sublayout(int maxWidth, int maxHeight) {
Field scroll = getField(0);
Field alpha = getField(1);
layoutChild(alpha, maxWidth, maxHeight);
layoutChild(scroll, maxWidth-alpha.getWidth(), maxHeight);
setPositionChild(scroll, 0, 0);
setPositionChild(alpha, maxWidth-alpha.getWidth(), 0);
setExtent(maxWidth, maxHeight);
}
};
hfm.add(createScrollContent());
hfm.add(createAlphabetJumpBar());
add(hfm);
}
private Field createScrollContent() {
Vector vocabulary = new Vector();
for (int ii=0; ii<alphabet.length; ii++)
vocabulary.addElement(alphabet[ii]);
scroller = new VerticalFieldManager(VERTICAL_SCROLL | USE_ALL_WIDTH) {
protected void sublayout(int maxWidth, int maxHeight) {
// Record the jump offsets
int y = 0;
for (int ii=0; ii<getFieldCount(); ii++) {
Field field = getField(ii);
layoutChild(field, maxWidth, maxHeight);
setPositionChild(field, 0, y);
if (field instanceof WordField) {
WordField object = (WordField)field;;
char character = object.getWord().toLowerCase().charAt(0);
int offset = ((int)character)-(int)alphabet[0].toLowerCase().charAt(0);
if (offset < 0 || offset > jump.length)
offset = jump.length-1;
while (offset >= 0 && offset < jump.length && jump[offset] == 0) {
jump[offset] = y;
offset--;
}
}
y += field.getHeight();
}
int offset = jump.length-1;
do {
jump[offset] = y;
offset--;
} while (offset >= 0 && jump[offset] == 0);
setExtent(maxWidth, maxHeight);
setVirtualExtent(maxWidth, y+10);
}
};
jump = new int[alphabet.length];
Font largeFont = Font.getDefault().derive(Font.PLAIN, 46);
for (int ii=0; ii<words.length; ii++) {
WordField wordField = new WordField(words[ii]);
wordField.setFont(largeFont);
scroller.add(wordField);
}
return scroller;
}
private Field createAlphabetJumpBar() {
VerticalFieldManager vfm = new VerticalFieldManager() {
protected void sublayout(int maxWidth, int maxHeight) {
int y = 0;
int width = 0;
double allowedAlphaHeight = (double)maxHeight / (double)getFieldCount();
for (int ii=0; ii<getFieldCount(); ii++) {
WordField field = (WordField)getField(ii);
layoutChild(field, maxWidth, (int)allowedAlphaHeight);
setPositionChild(field, 0, y);
y += field.getHeight();
double paddedY = Math.floor(allowedAlphaHeight*(ii+1));
if (y < paddedY) y = (int)paddedY;
width = Math.max(width, field.getWidth());
}
setExtent(width, maxHeight);
}
};
for (int ii=0; ii<alphabet.length; ii++) {
vfm.add(new AlphaField(alphabet[ii]){
protected boolean touchEvent(TouchEvent message) {
if (message.getEvent() == TouchEvent.UP) {
int startOffset = (int)alphabet[0].charAt(0);
int offset = ((int)getWord().charAt(0)) - startOffset;
final int y = offset == 0 ? 0 : jump[offset - 1];
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run() {
scroller.setVerticalScroll(y, true);
}});
}
return true;
}
});
}
return vfm;
}
class WordField extends LabelField {
private final String word;
public WordField(String word) {
super(word);
this.word = word;
}
public String getWord() { return word; }
}
Font alphaFont = null;
class AlphaField extends WordField {
public AlphaField(String word) {
super(word);
}
protected void layout(int width, int height) {
if (alphaFont == null)
alphaFont = Font.getDefault().derive(Font.PLAIN, height);
setExtent(alphaFont.getAdvance(getWord()), alphaFont.getHeight());
}
protected void paint(Graphics graphics) {
graphics.setFont(alphaFont);
graphics.drawText(getWord(), 0, 0);
}
}
/**
* For debugging.
* #see net.rim.device.api.ui.Screen#keyChar(char, int, int)
*/
protected boolean keyChar(char c, int status, int time) {
if ('o' == c) { // shows the jump offsets into the scroll field
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run() {
StringBuffer buf = new StringBuffer();
for (int ii=0; ii<jump.length; ii++) {
buf.append(alphabet[ii]+"="+jump[ii]);
if (ii<jump.length-1)
buf.append(",");
}
Status.show("offsets="+buf.toString());
}});
}
return super.keyChar(c, status, time);
}
}
}
You're using UiApplication.invokeLater in a few places where you're already on the UI event thread, so those are redundant - the debug code in keyChar and the setVerticalScroll call from the touchEvent handler. The Runnable is executed synchronously when you do an invokeLater from the UI thread, with no delay specified.
Are you sure you want to set the scroll explicitly? One option would be to set the focus on the WordField you are interested in, by calling setFocus(), then the OS will do the scrolling events to move that field on screen for you.
If you really need to explicitly set the vertical scroll, your problem may be that the touch event is already causing scroll, so setting it again causes problems. You can get around this by specifying a one millisecond delay for your invokeLater(...). This means your Runnable will be added to the event queue, instead of executing synchronously. That way the scroll won't be changed in the middle of another event call-stack.
Finally tracked down the issue - if the touchEvent for the alphabet label field returns a true then it locks up the main scroll field, if however return super.touchEvent(message) is called the scrolling happens and the scroll field can still be scrolled up and down by clicking on the screen.
This may be a bug in the BlackBerry OS or just the simulator. The Field.touchEvent() documentation for 6.0 recommends returning true if the method consumes the event; however doing so (at least in the above code) causes another UI field to loose the ability to detect touch events which would cause it to scroll.

Image Button in BlackBerry

How do I implement an image button in BlackBerry?
here you go, complete code:
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.ButtonField;
/**
* Button field with a bitmap as its label.
*/
public class BitmapButtonField extends ButtonField {
private Bitmap bitmap;
private Bitmap bitmapHighlight;
private boolean highlighted = false;
/**
* Instantiates a new bitmap button field.
*
* #param bitmap the bitmap to use as a label
*/
public BitmapButtonField(Bitmap bitmap, Bitmap bitmapHighlight) {
this(bitmap, bitmapHighlight, ButtonField.CONSUME_CLICK|ButtonField.FIELD_HCENTER|ButtonField.FIELD_VCENTER);
}
public BitmapButtonField(Bitmap bitmap, Bitmap bitmapHighlight, long style) {
super(style);
this.bitmap = bitmap;
this.bitmapHighlight = bitmapHighlight;
}
/* (non-Javadoc)
* #see net.rim.device.api.ui.component.ButtonField#layout(int, int)
*/
protected void layout(int width, int height) {
setExtent(getPreferredWidth(), getPreferredHeight());
}
/* (non-Javadoc)
* #see net.rim.device.api.ui.component.ButtonField#getPreferredWidth()
*/
public int getPreferredWidth() {
return bitmap.getWidth();
}
/* (non-Javadoc)
* #see net.rim.device.api.ui.component.ButtonField#getPreferredHeight()
*/
public int getPreferredHeight() {
return bitmap.getHeight();
}
/* (non-Javadoc)
* #see net.rim.device.api.ui.component.ButtonField#paint(net.rim.device.api.ui.Graphics)
*/
protected void paint(Graphics graphics) {
super.paint(graphics);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Bitmap b = bitmap;
if (highlighted)
b = bitmapHighlight;
graphics.drawBitmap(0, 0, width, height, b, 0, 0);
}
public void setHighlight(boolean highlight)
{
this.highlighted = highlight;
}
}
Use RIM's Advanced UI Pack.
http://supportforums.blackberry.com/t5/Java-Development/Implement-advanced-buttons-fields-and-managers/ta-p/488276
This contains a BitmapButton field and a great number of of useful UI tools.
(No doubt Reflogs example is good, but I think for new BB developers landing on this page the Advanced UI pack is more beneficial)
perfect ImageButton for Blackberry , According to user point of view a Imagebutton should have four states
1. Normal
2. Focus
3. Selected Focus
4. Selected unfocus
the Following code maintain all four states (Field-Change-Listener and Navigation)
if you want to maintain all four states than use 1st Constructor, If you just want to handle Focus/Un-Focu state of the button than use 2nd one
########################################
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
public class ImageButton extends Field
{
Bitmap mNormalIcon;
Bitmap mFocusedIcon;
Bitmap mActiveNormalIcon;
Bitmap mActiveFocusedIcon;
Bitmap mActiveBitmap;
String mActiveText;
int mHeight;
int mWidth;
boolean isStateActive = false;
boolean isTextActive = false;
public boolean isStateActive()
{
return isStateActive;
}
public ImageButton(Bitmap normalIcon, Bitmap focusedIcon)
{
super(Field.FOCUSABLE | FIELD_VCENTER);
mNormalIcon = normalIcon;
mFocusedIcon = focusedIcon;
mActiveBitmap = normalIcon;
mActiveFocusedIcon = focusedIcon;
mActiveNormalIcon = normalIcon;
// isTextActive = false;
}
public ImageButton(Bitmap normalIcon, Bitmap focusedIcon, Bitmap activeNormalIcon, Bitmap activeFocusedIcon)
{
super(Field.FOCUSABLE | FIELD_VCENTER);
mNormalIcon = normalIcon;
mFocusedIcon = focusedIcon;
mActiveFocusedIcon = activeFocusedIcon;
mActiveNormalIcon = activeNormalIcon;
mActiveBitmap = normalIcon;
// isTextActive = true;
}
protected void onFocus(int direction)
{
if ( !isStateActive )
{
mActiveBitmap = mFocusedIcon;
}
else
{
mActiveBitmap = mActiveFocusedIcon;
}
}
protected void onUnfocus()
{
super.onUnfocus();
if ( !isStateActive )
{
mActiveBitmap = mNormalIcon;
}
else
{
mActiveBitmap = mActiveNormalIcon;
}
}
protected boolean navigationClick(int status, int time)
{
mActiveBitmap = mActiveNormalIcon;
toggleState();
invalidate();
fieldChangeNotify(1);
return true;
}
public void toggleState()
{
isStateActive = !isStateActive;
}
public int getPreferredWidth()
{
return mActiveBitmap.getWidth() + 20;
}
public int getPreferredHeight()
{
return mActiveBitmap.getHeight() + 10;
}
protected void layout(int width, int height)
{
mWidth = getPreferredWidth();
mHeight = getPreferredHeight();
setExtent(mWidth, mHeight);
}
protected void paint(Graphics graphics)
{
graphics.drawBitmap(0, 5, mWidth, mHeight, mActiveBitmap, 0, 0);
// graphics.setColor(0xff0000);
// graphics.drawText(mActiveText, ( mActiveBitmap.getWidth() -
// this.getFont().getAdvance("ON") ) / 2, mActiveBitmap.getHeight());
}
protected void drawFocus(Graphics graphics, boolean on)
{
}
public void activate()
{
mActiveBitmap = mActiveNormalIcon;
isStateActive = true;
invalidate();
}
public void deactivate()
{
mActiveBitmap = mNormalIcon;
isStateActive = false;
invalidate();
}
}
easiest way to do that:
step 1:draw a image with specific coordinates(imageX,imageY).
step 2:add a method in your Code:
void pointerControl(int x, int y) {
if (x>imageX && x<imageX+imageName.getWidth() && y>imageY && y < imageY+imageName.getHeight) {
//to do code here
}
}
where imageName:name of image
imageX=x coordinate of image(Top-Left)
imageY=y coordinate of image(Top-Left)

Resources