i want to create sub menu for a BB application
when i click on menu item it shows
Option 1
Option 2
Option 3
When i click on option 3 it should display
1
2
3
as sub menu items..
using j2me + eclipse
Always wanted to do this )
alt text http://img380.imageshack.us/img380/3874/menugy.jpg
class Scr extends MainScreen {
SubMenu menu = new SubMenu();
public Scr() {
for (int i = 0; i < 3; i++) {
SubMenu sMenu = new SubMenu();
menu.add(new SubMenuItem(i + " item", sMenu));
for (int k = 0; k < 3; k++) {
SubMenu sSMenu = new SubMenu();
sMenu.add(new SubMenuItem(i + "-" + k + " item", sSMenu));
for (int l = 0; l < 3; l++) {
sSMenu
.add(new SubMenuItem(i + "-" + k + "-" + l
+ " item"));
}
}
}
add(new LabelField("testing menu", FOCUSABLE) {
protected void makeContextMenu(ContextMenu contextMenu) {
menu.mRectangle.x = this.getContentRect().X2();
menu.mRectangle.y = this.getContentRect().Y2();
Ui.getUiEngine().pushScreen(menu);
EventInjector.invokeEvent(new KeyEvent(KeyEvent.KEY_DOWN,
Characters.ESCAPE, 0));
}
});
}
}
class SubMenu extends PopupScreen implements ListFieldCallback {
private static final int MAX_WIDTH = Font.getDefault().getAdvance(
"max menu item text");
XYRect mRectangle = new XYRect();
Vector mSubMenuItems = new Vector();
ListField mListField;
public SubMenu() {
super(new SubMenuItemManager(), DEFAULT_CLOSE);
int rowHeight = getFont().getHeight() + 2;
mListField = new ListField() {
protected boolean navigationClick(int status, int time) {
runMenuItem(getSelectedIndex());
return super.navigationClick(status, time);
}
};
mListField.setRowHeight(rowHeight);
add(mListField);
mListField.setCallback(this);
updateMenuItems();
}
public void add(SubMenuItem subMenuItem) {
mSubMenuItems.addElement(subMenuItem);
subMenuItem.mMenu = this;
updateMenuItems();
}
private void updateMenuItems() {
int rowCounts = mSubMenuItems.size();
mRectangle.width = getMaxObjectToStringWidth(mSubMenuItems);
mRectangle.height = mListField.getRowHeight() * rowCounts;
mListField.setSize(rowCounts);
}
private void runMenuItem(int index) {
SubMenuItem item = (SubMenuItem) get(mListField, index);
if (null != item.mSubMenu) {
item.mSubMenu.setSubMenuPosition(getSubMenuRect(index));
Ui.getUiEngine().pushScreen(item.mSubMenu);
} else {
item.run();
}
}
private XYRect getSubMenuRect(int index) {
SubMenuItem item = (SubMenuItem) get(mListField, index);
XYRect result = item.mSubMenu.mRectangle;
result.x = mRectangle.x + mRectangle.width;
result.y = mRectangle.y + mListField.getRowHeight() * index;
int testWidth = Display.getWidth() - (mRectangle.width + mRectangle.x);
if (testWidth < result.width) {
result.width = testWidth;
}
int testHeight = Display.getHeight()
- (mRectangle.height + mRectangle.y);
if (testHeight < result.height)
result.height = testHeight;
return result;
}
public void setSubMenuPosition(XYRect rect) {
mRectangle = rect;
}
protected void sublayout(int width, int height) {
super.sublayout(mRectangle.width, mRectangle.height);
setPosition(mRectangle.x, mRectangle.y);
setExtent(mRectangle.width, mRectangle.height);
}
private int getMaxObjectToStringWidth(Vector objects) {
int result = 0;
for (int i = 0; i < objects.size(); i++) {
int width = getFont().getAdvance(objects.elementAt(i).toString());
if (width > result) {
if (width > MAX_WIDTH) {
result = MAX_WIDTH;
break;
} else {
result = width;
}
}
}
return result;
}
public void drawListRow(ListField field, Graphics g, int i, int y, int w) {
// Draw the text.
String text = get(field, i).toString();
g.setColor(Color.WHITE);
g.drawText(text, 0, y, DrawStyle.ELLIPSIS, w);
}
public Object get(ListField listField, int index) {
return mSubMenuItems.elementAt(index);
}
public int getPreferredWidth(ListField listField) {
return mRectangle.width;
}
public int indexOfList(ListField listField, String prefix, int start) {
return 0;
}
}
class SubMenuItemManager extends VerticalFieldManager {
public SubMenuItemManager() {
super(USE_ALL_HEIGHT | USE_ALL_WIDTH);
}
public int getPreferredWidth() {
return ((SubMenu) getScreen()).mRectangle.width;
}
public int getPreferredHeight() {
return ((SubMenu) getScreen()).mRectangle.height;
}
protected void sublayout(int maxWidth, int maxHeight) {
maxWidth = getPreferredWidth();
maxHeight = getPreferredHeight();
super.sublayout(maxWidth, maxHeight);
setExtent(maxWidth, maxHeight);
}
}
class SubMenuItem implements Runnable {
String mName;
SubMenu mMenu;
SubMenu mSubMenu;
public SubMenuItem(String name) {
this(name, null);
}
public SubMenuItem(String name, SubMenu subMenu) {
mName = name;
mSubMenu = subMenu;
}
public String toString() {
return mName;
}
public void run() {
}
}
Submenus are not part of the standard BlackBerry API. If you want to do this, you'll have to make your own custom menu+submenu control.
Related
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page
{
public enum Suit
{
Club,
Diamond,
Heart,
Spade
}
public static int i = 0;
public class Card
{
private Suit suit;
private int rank;
private string pictureUrl;
public Suit Suit
{
get { return suit;}
set { suit = value; }
}
public int Rank
{
get { return rank; }
set { rank = value; }
}
public string PictureUrl
{
get { return pictureUrl; }
set { pictureUrl = value; }
}
public Card(Suit suit, int rank, string pictureUrl)
{
this.suit = suit;
this.rank = rank;
this.pictureUrl = pictureUrl;
}
}
protected void InitDeck(List<Card> deck)
{
for (int suit = 0; suit < 4; suit++)
for (int rank = 0; rank < 13; rank++)
{
string strPath = "Images\\" + (suit * 13 + rank).ToString() + ".png";
deck.Add(new Card((Suit)suit, rank + 2, strPath));
}
}
protected void InitGameBoard(Card[,] gameBoard, List<Card> deck)
{
Random rnd = new Random();
int rndPosition;
for(int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
{
if (i == 4 && j == 4)
{
gameBoard[i, j] = new Card(0, 100, "Images\\b1fv.png");
}
else
{
rndPosition = rnd.Next(0, deck.Count);
gameBoard[i, j] = deck[rndPosition];
deck.RemoveAt(rndPosition);
}
}
}
protected void DrawTable(Card[,] gameBoard)
{
Table gameTable = new Table();
gameTable.GridLines = GridLines.Both;
gameTable.BorderWidth = 4;
gameTable.ID = "gameTable";
ImageButton imgBtn = null;
for (int i = 0; i < 5; i++)
{
TableRow tblRow = new TableRow();
for (int j = 0; j < 5; j++)
{
TableCell tblCell = new TableCell();
tblCell.HorizontalAlign = HorizontalAlign.Center;
imgBtn = new ImageButton();
imgBtn.ID = i.ToString() + j.ToString();
imgBtn.Width = 80;
imgBtn.Height = 105;
imgBtn.ImageUrl = gameBoard[i, j].PictureUrl;
imgBtn.Click += new ImageClickEventHandler(Checking);
tblCell.Controls.Add(imgBtn);
tblRow.Cells.Add(tblCell);
}
gameTable.Rows.Add(tblRow);
}
Panel1.Controls.Add(gameTable);
}
protected void Checking(System.Object sender, System.EventArgs e)
{
ImageButton imgBtn = (ImageButton)sender;
int imgBtnIdNo = int.Parse(imgBtn.ID);
Label1.Text = i.ToString();
}
protected void Page_Load(object sender, EventArgs e)
{
List<Card> deck = new List<Card>();
Card[,] gameBoard = new Card[5, 5];
InitDeck(deck);
InitGameBoard(gameBoard, deck);
DrawTable(gameBoard);
}
}
This a win-form game i'm bulding, where a random 5 X 5 table is generated filled with cards except a blank cell, you need to press image button around a blanked cell, to switch their places and bulding Rows of poker made hands, but evrey time im pressing an image button the table keep generating.
By default, a button press sends the event to the server (and the page gets re-loaded). To handle it in the client, you need to use the OnClientClick property (http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx)
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;
}
}
Do you know some way to programmaticaly show different typing indicators on the screen?
I know I can simply draw bitmap but I'd like to do it universally for any RIM OS version.
Also, there is a setMode(int) function in 4.2.1 but in 4.3 it's already deprecated...
Any suggestions will be helpful, thanks!
since there is no alternatives, I made a sample with provided images:
alt text http://img42.imageshack.us/img42/6692/typeindicator.jpg
alt text http://img3.imageshack.us/img3/5259/inputind.jpg
custom Title Field class code:
class TITitleField extends Field implements DrawStyle {
static final boolean mIsDimTheme = Integer.parseInt(DeviceInfo
.getDeviceName().substring(0, 4)) < 8900;
static final Bitmap ALT = Bitmap.getBitmapResource(mIsDimTheme ?
"typ_ind_alt_mode_Gen_Zen_328560_11.jpg" :
"typ_ind_alt_mode_Precsn_Zen_392908_11.jpg");
static final Bitmap MULTITAP = Bitmap.getBitmapResource(mIsDimTheme ?
"typ_ind_mltap_mode_Gen_Zen_328975_11.jpg" :
"typ_ind_mutlitap_mode_Precsn_Zen_452907_11.jpg");
static final Bitmap NUMLOCK = Bitmap
.getBitmapResource(mIsDimTheme ?
"typ_ind_num_lock_Gen_Zen_328568_11.jpg" :
"typ_ind_num_lock_Precsn_Zen_392925_11.jpg");
static final Bitmap SHIFT = Bitmap.getBitmapResource(mIsDimTheme ?
"typ_ind_shift_mode_Gen_Zen_328574_11.jpg" :
"typ_ind_shift_mode_Precsn_Zen_392931_11.jpg");
public static final int MODE_NONE = 0;
public static final int MODE_ALT = 1;
public static final int MODE_MULTITAP = 2;
public static final int MODE_NUMLOCK = 3;
public static final int MODE_SHIFT = 4;
public void setTypingIndicatorMode(int mode) {
mMode = mode;
updateLayout();
}
public int getTypingIndicatorMode()
{
return mMode;
}
int mWidth = 0;
int mMode = 0;
String mTitle = "";
XYRect mIndicatorDestRect = new XYRect();
public TITitleField() {
this("");
}
public TITitleField(String title) {
mTitle = title;
}
protected void paint(Graphics graphics) {
graphics.drawText(mTitle, 0, 0, LEFT | ELLIPSIS, mWidth);
if (0 != mMode) {
graphics.drawBitmap(mIndicatorDestRect,getIndicator(mMode),0,0);
}
}
private static Bitmap getIndicator(int mode) {
Bitmap result = null;
switch (mode) {
case MODE_ALT:
result = ALT;
break;
case MODE_MULTITAP:
result = MULTITAP;
break;
case MODE_NUMLOCK:
result = NUMLOCK;
break;
case MODE_SHIFT:
result = SHIFT;
break;
case MODE_NONE:
break;
default:
break;
}
return result;
}
protected void layout(int width, int height) {
mWidth = width;
if (0 != mMode) {
Bitmap indicator = getIndicator(mMode);
mIndicatorDestRect.width = indicator.getWidth();
mIndicatorDestRect.height = indicator.getHeight();
mIndicatorDestRect.y = 0;
mIndicatorDestRect.x = mWidth - mIndicatorDestRect.width;
}
setExtent(width, getPreferredHeight());
}
public int getPreferredHeight() {
int height = getFont().getHeight() + 4;
if (0 != mMode) {
int indicatorHeight = getIndicator(mMode).getHeight();
height = Math.max(height, indicatorHeight);
}
return height;
}
}
Sample of use code:
class Scr extends MainScreen {
static final TITitleField mTitle = new TITitleField("Start");
public Scr() {
this.setTitle(mTitle);
}
protected void makeMenu(Menu menu, int instance) {
super.makeMenu(menu, instance);
int typingIndicatorMode = mTitle.getTypingIndicatorMode();
if(typingIndicatorMode != mTitle.MODE_NONE)
menu.add(new MenuItem("None Mode", 0, 0) {
public void run() {
mTitle.setTypingIndicatorMode(mTitle.MODE_NONE);
}
});
if(typingIndicatorMode != mTitle.MODE_ALT)
menu.add(new MenuItem("Alt Mode", 0, 0) {
public void run() {
mTitle.setTypingIndicatorMode(mTitle.MODE_ALT);
}
});
if(typingIndicatorMode != mTitle.MODE_MULTITAP)
menu.add(new MenuItem("Multitap Mode", 0, 0) {
public void run() {
mTitle.setTypingIndicatorMode(mTitle.MODE_MULTITAP);
}
});
if(typingIndicatorMode != mTitle.MODE_NUMLOCK)
menu.add(new MenuItem("NumLock Mode", 0, 0) {
public void run() {
mTitle.setTypingIndicatorMode(mTitle.MODE_NUMLOCK);
}
});
if(typingIndicatorMode != mTitle.MODE_SHIFT)
menu.add(new MenuItem("Shift Mode", 0, 0) {
public void run() {
mTitle.setTypingIndicatorMode(mTitle.MODE_SHIFT);
}
});
}
}
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) {
}
}
Is it possible to add a CheckBoxField to a TreeField in BlackBerry ?
If yes, how do I do it?
Same trick as with ListBox CheckBoxes:
alt text http://img441.imageshack.us/img441/5120/checkboxtree.jpg
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();
}
});
}
}
sample of use:
class Scr extends MainScreen {
public Scr() {
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);
}
}