BlackBerry - Custom menu toolbar - user-interface

I'm a beginner in BlackBerry programming, I need to replace in my application the default menu (when you press the menu button) by a custom menu, horizontal. The best to describe is I want the same result as the WeatherEye application for BlackBerry...
alt text http://www.blackberrybing.com/resource/pics/201002/WeatherEye-OS-45.jpg
I know how to create the default menu, but this one I have no idea!
Thank you,

What you will need to do is:
create SizebleVFManager (contentManager) as an extension of VerticalFieldManager
set display width and height = (display height - menu height) size to contentManager
add contentManager to screen
create HorizontalFieldManager (menuManager)
create BitmapButtonField (menuButton) as an extension of ButtonField
set FieldChangeListeners to menuButtons
add menuButtons to menuManager
add menuManager to screen
Sample of SizebleVFManager :
class SizebleVFManager extends VerticalFieldManager
{
int mWidth = 0;
int mHeight = 0;
public SizebleVFM(int width, int height, long style) {
super(style);
mWidth = width;
mHeight = height;
}
public SizebleVFM(int width, int height) {
mWidth = width;
mHeight = height;
}
public int getPreferredWidth() {
return mWidth;
}
public int getPreferredHeight() {
return mHeight;
}
protected void sublayout(int width, int height) {
width = getPreferredWidth();
height = getPreferredHeight();
super.sublayout(width, height);
setExtent(width, height);
}
}
...
SizebleVFManager contentManager =
new SizebleVFManager(Display.getWidth(), Display.getHeight(),
VERTICAL_SCROLL|VERTICAL_SCROLLBAR);
See also
sample of BitmapButtonField and Toolbar
PS though its better to use standard menu...
UPDATE
If you want to disable default menu functionality, cancel MENU keydown:
protected boolean keyDown(int keycode, int time) {
if(Keypad.KEY_MENU == Keypad.key(keycode))
{
return true;
}
else
return super.keyDown(keycode, time);
}
UPDATE
I've installed that wonderful weather application and understood this sample may be more alike with several improvements:
use CyclicHFManager as an extension of HorizontalFieldManager
show/hide menuManager on Menu button click
CyclicHFManager is a manager which will keep focus on the same place visually and run all fields over, in cycle. Like in BlackBerry - Custom centered cyclic HorizontalFieldManager
class CyclicHFManager extends HorizontalFieldManager {
int mFocusedFieldIndex = 0;
boolean mCyclicTurnedOn = false;
public void focusChangeNotify(int arg0) {
super.focusChangeNotify(arg0);
if (mCyclicTurnedOn) {
int focusedFieldIndexNew = getFieldWithFocusIndex();
if (focusedFieldIndexNew != mFocusedFieldIndex) {
if (focusedFieldIndexNew - mFocusedFieldIndex > 0)
switchField(0, getFieldCount() - 1);
else
switchField(getFieldCount() - 1, 0);
}
}
else
{
mFocusedFieldIndex = getFieldWithFocusIndex();
}
}
private void switchField(int prevIndex, int newIndex) {
Field field = getField(prevIndex);
delete(field);
insert(field, newIndex);
}
}
alt text http://img109.imageshack.us/img109/6176/toolbarj.jpg
And whole code sample:
abstract class AScreen extends MainScreen {
boolean mMenuEnabled = false;
SizebleVFManager mContentManager = null;
CyclicHFManager mMenuManager = null;
public AScreen() {
mContentManager = new SizebleVFManager(Display.getWidth(), Display
.getHeight(), VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
add(mContentManager);
// mMenuManager = new CyclicHFManager(Display.getWidth(), 60);
mMenuManager = new CyclicHFManager();
mMenuManager.setBorder(BorderFactory.createBevelBorder(new XYEdges(4,
0, 0, 0), new XYEdges(Color.DARKBLUE, 0, 0, 0), new XYEdges(
Color.WHITE, 0, 0, 0)));
mMenuManager.setBackground(BackgroundFactory
.createLinearGradientBackground(Color.DARKBLUE, Color.DARKBLUE,
Color.LIGHTBLUE, Color.LIGHTBLUE));
for (int i = 0; i < 10; i++) {
Bitmap nBitmap = new Bitmap(60, 60);
Graphics g = new Graphics(nBitmap);
g.setColor(Color.DARKBLUE);
g.fillRect(0, 0, 60, 60);
g.setColor(Color.WHITE);
g.drawRect(0, 0, 60, 60);
Font f = g.getFont().derive(Font.BOLD, 40);
g.setFont(f);
String text = String.valueOf(i);
g.drawText(text, (60 - f.getAdvance(text)) >> 1, (60 - f
.getHeight()) >> 1);
Bitmap fBitmap = new Bitmap(60, 60);
g = new Graphics(fBitmap);
g.setColor(Color.DARKBLUE);
g.fillRect(0, 0, 60, 60);
g.setColor(Color.GOLD);
g.drawRect(0, 0, 60, 60);
g.setFont(f);
g.drawText(text, (60 - f.getAdvance(text)) >> 1, (60 - f
.getHeight()) >> 1);
BitmapButtonField button = new BitmapButtonField(nBitmap, fBitmap,
fBitmap);
button.setCookie(String.valueOf(i));
button.setPadding(new XYEdges(0, 18, 0, 18));
button.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
Dialog.inform("Button # " + (String) field.getCookie());
}
});
mMenuManager.add(button);
}
}
protected boolean keyDown(int keycode, int time) {
if (Keypad.KEY_MENU == Keypad.key(keycode)) {
if (mMenuManager.getManager() != null) {
delete(mMenuManager);
mMenuManager.mCyclicTurnedOn = false;
mContentManager.updateSize(Display.getWidth(), Display
.getHeight());
} else {
add(mMenuManager);
mMenuManager.getField(2).setFocus();
mMenuManager.mCyclicTurnedOn = true;
mContentManager.updateSize(Display.getWidth(), Display
.getHeight()
- mMenuManager.getHeight());
}
return true;
} else
return super.keyDown(keycode, time);
}
}
class FirstScreen extends AScreen {
public FirstScreen() {
mContentManager.add(new LabelField("This is a first screen"));
}
}
public class ToolbarMenuApp extends UiApplication {
public ToolbarMenuApp() {
pushScreen(new FirstScreen());
}
public static void main(String[] args) {
(new ToolbarMenuApp()).enterEventDispatcher();
}
}

Related

how can i make the unity gui window dragable

i am trying to make my window dragable
i'm currently making a multiplayer game and the status to be shown has this window
public bool finishSession = false;
public bool showHelp = false;
private ArrayList messages = new ArrayList();
private string currentTime = "";
private string newMessage = "";
private Vector2 windowScrollPosition;
private SmartFox smartFox;
private GUIStyle windowStyle;
private GUIStyle userEventStyle;
private GUIStyle systemStyle;
public Rect rctWindow;
public float windowPanelPosX;
public float windowPanelPosY;
public float windowPanelWidth;
public float windowPanelHeight;
public StatusWindow() {
smartFox = SmartFoxConnection.Connection;
}
public void AddSystemMessage(string message) {
messages.Add(new StatusMessage(StatusMessage.StatusType.SYSTEM, message));
windowScrollPosition.y = 100000;
}
public void AddStatusMessage(string message) {
messages.Add(new StatusMessage(StatusMessage.StatusType.STATUS, message));
windowScrollPosition.y = 100000;
}
public void AddTimeMessage(string message) {
//messages.Add(new StatusMessage(StatusMessage.StatusType.TIME, message));
//windowScrollPosition.y = 100000;
currentTime = message;
}
public void Draw(float panelPosX, float panelPosY, float panelWidth, float panelHeight) {
windowPanelPosX = panelPosX;
windowPanelPosY = panelPosY;
windowPanelWidth = panelWidth;
windowPanelHeight = panelHeight;
// Status history panel
rctWindow = new Rect(windowPanelPosX, windowPanelPosY, windowPanelWidth, windowPanelHeight);
rctWindow = GUI.Window (1, rctWindow, DoMyWindow, "Interreality Portal Status", GUI.skin.GetStyle("window"));
GUI.DragWindow();
}
void DoMyWindow(int windowID)
{
windowStyle = GUI.skin.GetStyle("windowStyle");
systemStyle = GUI.skin.GetStyle("systemStyle");
userEventStyle = GUI.skin.GetStyle("userEventStyle");
//Cuadro blanco
GUILayout.BeginArea (new Rect (10, 25, windowPanelWidth - 20, windowPanelHeight - 70), GUI.skin.GetStyle ("whiteBox"));
GUILayout.BeginVertical ();
//General information area
if (smartFox != null && smartFox.LastJoinedRoom != null) {
GUILayout.Label ("Current room: " + smartFox.LastJoinedRoom.Name);
//if (currentGameState == GameState.RUNNING ) {
//GUILayout.Label(trisGameInstance.GetGameStatus()); //ACPR
//}
}
GUILayout.Label ("Activity: 1 - Construct");
GUILayout.Label ("Elapsed time: " + currentTime);
//Message area
windowScrollPosition = GUILayout.BeginScrollView (windowScrollPosition);
foreach (StatusMessage message in messages) {
DrawStatusMessage (message);
}
GUILayout.EndScrollView ();
//Cierra cuadro blanco
GUILayout.EndVertical ();
GUILayout.EndArea ();
//Logout area
GUILayout.BeginArea (new Rect (windowPanelWidth / 2, windowPanelHeight - 70 + 30, windowPanelWidth / 2 + 10, 30));//, GUI.skin.GetStyle("whiteBox"));
GUILayout.BeginHorizontal ();
if (GUILayout.Button ("Help", GUI.skin.GetStyle ("greenBtn"))) {
showHelp = true;
}
GUILayout.Space (10);
if (GUILayout.Button ("End Session", GUI.skin.GetStyle ("redBtn"))) {
finishSession = true;
}
GUILayout.EndHorizontal ();
GUILayout.EndArea ();
GUI.DragWindow();
}
private void DrawStatusMessage(StatusMessage message) {
GUILayout.BeginHorizontal();
GUILayout.Space(5);
switch (message.GetStatusType()) {
case StatusMessage.StatusType.SYSTEM:
GUILayout.Label(message.GetMessage(), systemStyle);
break;
case StatusMessage.StatusType.STATUS:
GUILayout.Label(message.GetMessage(), windowStyle);
break;
case StatusMessage.StatusType.TIME:
GUILayout.Label(message.GetMessage(), userEventStyle);
break;
default:
// Ignore and dont print anything
break;
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(1);
GUI.DragWindow();
}
class StatusMessage {
public enum StatusType {
IGNORE = 0,
SYSTEM,
STATUS,
TIME,
};
private StatusType type;
private string message;
public StatusMessage() {
type = StatusType.IGNORE;
message = "";
}
public StatusMessage(StatusType type, string message) {
this.type = type;
this.message = message;
}
public StatusType GetStatusType() {
return type;
}
public string GetMessage() {
return message;
}
}
}
but when i'mm trying to drag the window it doesn't drag it
i tried a simpler class with jnothing that works fine but when i call this window it doesn't drag
StatusWindow statusWindow = null;
void Start(){
statusWindow = new StatusWindow();
}
public Rect windowRect = new Rect(20, 20, 120, 50);
void OnGUI() {
windowRect = GUI.Window(0, windowRect, DoMyWindow, "My Window");
statusWindow.Draw (100, 100, 100, 100);
}
void DoMyWindow(int windowID) {
GUI.Button(new Rect(10, 20, 100, 20), "Can't drag me");
GUI.DragWindow();
}
If anyone who knows much about Unity GUI can help that would be great

GWT - Fading in/out a background image

I have a custom class as follows which works fine, the button grows/shrinks to accomodate the text and the bg image changes on a click.
Probem I want to solve is how to "fadeIN" one or other image when clicked/notClicked is called
Here is my code
public ExpandingOvalButton(String text) {
if (text.length() > 15) {
label.getElement().getStyle().setFontSize(20, Unit.PX);
} else {
label.getElement().getStyle().setFontSize(30, Unit.PX);
}
int width = 120;
initWidget(panel);
label.setText(text);
// width = width + (text.length() * 8);
String widthStr = width + "px";
image.setWidth(widthStr);
image.setHeight("100px");
button = new PushButton(image);
button.setWidth(widthStr);
button.setHeight("50px");
panel.add(button, 0, 0);
panel.add(label, 18, 14);
}
public void isClicked()
{
image.setUrl("images/rectangle_green.png");
}
public void unClicked()
{
image.setUrl("images/rectangle_blue.png");
}
#Override
public HandlerRegistration addClickHandler(ClickHandler handler) {
return addDomHandler(handler, ClickEvent.getType());
}
public void setButtonEnabled(boolean enabled) {
// panel.setVisible(enabled);
// this.label.setVisible(enabled);
this.button.setVisible(enabled);
}
Here's a general utility class to fade any element:
public class ElementFader {
private int stepCount;
public ElementFader() {
this.stepCount = 0;
}
private void incrementStep() {
stepCount++;
}
private int getStepCount() {
return stepCount;
}
public void fade(final Element element, final float startOpacity, final float endOpacity, int totalTimeMillis) {
final int numberOfSteps = 30;
int stepLengthMillis = totalTimeMillis / numberOfSteps;
stepCount = 0;
final float deltaOpacity = (float) (endOpacity - startOpacity) / numberOfSteps;
Timer timer = new Timer() {
#Override
public void run() {
float opacity = startOpacity + (getStepCount() * deltaOpacity);
DOM.setStyleAttribute(element, "opacity", Float.toString(opacity));
incrementStep();
if (getStepCount() == numberOfSteps) {
DOM.setStyleAttribute(element, "opacity", Float.toString(endOpacity));
this.cancel();
}
}
};
timer.scheduleRepeating(stepLengthMillis);
}
}
Calling code for instance:
new ElementFader().fade(image.getElement(), 0, 1, 1000); // one-second fade-in
new ElementFader().fade(image.getElement(), 1, 0, 1000); // one-second fade-out
You could use GwtQuery. It provides fadeIn & fadeOut effects (and many other JQuery goodies), it is cross-browser compatible and seems to be pretty active.

canvas.DrawBitmap() executing at onPostExecute in AsyncTask but Bitmap not displaying

I am calling invalidate() which is calling onDraw(). The bitmap that I wish to show on the screen is not being displayed after running doInBackGround(). Can anyone help?
Here is what I have tested out so far.
When I place the same line of code
canvas.drawBitmap();
in onPreExecute() it works, but in onPostExecute() it does not display the expected results.
This is my code:
public class FloorAppActivity extends Activity {
private Context globalContext;
private Point displaySize;
private int displayWidth;
private int displayHeight;
private String floorID;
private String floorName;
private String floorGridNumStr;
private int floorGridNum;
private String floorNumStr;
private int positionX;
private int positionY;
private int XCoord;
private int YCoord;
private int ZCoord;
private float signalStr;
private Integer dBm;
private Bitmap floorPlan;
private Bitmap userMark;
private Bitmap redPin;
private FloorView floorView;
private Connection conn = null;
private Canvas canvas=null;
private int newScrollRectX=0;
private int newScrollRectY=0;
private Paint paint;
private boolean a = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
globalContext = this;
floorID = getIntent().getStringExtra("floorID");
floorName = getIntent().getStringExtra("floorName");
positionX = getIntent().getIntExtra("userPositionX",-1);
positionY = getIntent().getIntExtra("userPositionY",-1);
dBm = getIntent().getIntExtra("BestSignal", -1);
//Get the grid number
if(Integer.parseInt(floorName.substring(floorName.lastIndexOf("_")+1))<10)
floorGridNumStr = floorName.substring(8, 9);
else
floorGridNumStr = floorName.substring(8, 10);
floorGridNum = Integer.parseInt(floorGridNumStr);
floorNumStr = floorName.substring(5,7);
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
displaySize = new Point();
try {
// GetSize is not available in older models of Android
display.getSize(displaySize);
} catch (java.lang.NoSuchMethodError ignore) { // Older device
displaySize.x = display.getWidth();
displaySize.y = display.getHeight();
}
try {
InputStream source = getAssets().open(floorID);
floorPlan = BitmapFactory.decodeStream(source);
displayWidth = Math.min(displaySize.x, floorPlan.getWidth());
displayHeight = Math.min(displaySize.y, floorPlan.getHeight());
userMark = BitmapFactory.decodeResource(getResources(),R.drawable.star);
redPin = BitmapFactory.decodeResource(getResources(),R.drawable.redpin);
floorView = new FloorView(this);
setContentView(floorView);
}
catch (IOException e) {
MapServerAPI server = new MapServerAPI(globalContext,"Retrieving floor plan. Please wait...") {
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (bitmap == null)
Toast.makeText(globalContext, "Error in retrieving floor plan!", Toast.LENGTH_LONG).show();
else {
floorPlan = bitmap;
displayWidth = Math.min(displaySize.x, floorPlan.getWidth());
displayHeight = Math.min(displaySize.x, floorPlan.getHeight());
userMark = BitmapFactory.decodeResource(getResources(),R.drawable.star);
redPin = BitmapFactory.decodeResource(getResources(),R.drawable.redpin);
floorView = new FloorView(globalContext);
setContentView(floorView);
}
}
};
server.execute(floorID);
}
}
#Override
public void onResume() {
super.onResume();
registerReceiver(broadcastReceiver,new IntentFilter("FingerPrint_LOCATION_UPDATE"));
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
// listen for user location change
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String result = intent.getStringExtra("location");
Toast.makeText(context,result,Toast.LENGTH_LONG).show();
String floorId = intent.getStringExtra("floorID");
floorName = intent.getStringExtra("name");
dBm = intent.getIntExtra("BestSignal", -1);
int userLocationX = intent.getIntExtra("userPositionX",-1);
int userLocationY = intent.getIntExtra("userPositionY",-1);
//Get the grid number
if(Integer.parseInt(floorName.substring(floorName.lastIndexOf("_")+1))<10)
floorGridNumStr = floorName.substring(8, 9);
else
floorGridNumStr = floorName.substring(8, 10);
floorGridNum = Integer.parseInt(floorGridNumStr);
floorNumStr = floorName.substring(5,7);
if(!floorId.equals(floorID)){
positionX = userLocationX;
positionY = userLocationY;
InputStream source=null;
try {
source = getAssets().open(floorID);
} catch (IOException e) {
}
floorPlan = BitmapFactory.decodeStream(source);
floorView.postInvalidate();
}
}
};
private class FloorView extends View {
private Rect displayRect; //rect we display to
private Rect scrollRect; //rect we scroll over our bitmap with
private int scrollRectX = 0; //current left location of scroll rect
private int scrollRectY = 0; //current top location of scroll rect
private float scrollByX = 0; //x amount to scroll by
private float scrollByY = 0; //y amount to scroll by
private float startX = 0; //track x from one ACTION_MOVE to the next
private float startY = 0; //track y from one ACTION_MOVE to the next
public FloorView(Context context) {
super(context);
// Destination rect for our main canvas draw. It never changes.
displayRect = new Rect(0, 0, displayWidth, displayHeight);
// Scroll rect: this will be used to 'scroll around' over the
// bitmap in memory.
if (positionX + displayWidth / 2 > floorPlan.getWidth())
scrollRectX = floorPlan.getWidth() - displayWidth;
else
scrollRectX = positionX - displayWidth / 2;
if (scrollRectX < 0)
scrollRectX = 0;
if (positionY + displayHeight / 2 > floorPlan.getHeight())
scrollRectY = floorPlan.getHeight() - displayHeight;
else
scrollRectY = positionY - displayHeight / 2;
if (scrollRectY < 0)
scrollRectY = 0;
scrollRect = new Rect(scrollRectX, scrollRectY, displayWidth, displayHeight);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Remember our initial down event location.
startX = event.getRawX();
startY = event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
float x = event.getRawX();
float y = event.getRawY();
// Calculate move update. This will happen many times
// during the course of a single movement gesture.
scrollByX = x - startX; //move update x increment
scrollByY = y - startY; //move update y increment
startX = x; //reset initial values to latest
startY = y;
invalidate(); //force a redraw
break;
}
return true; //done with this event so consume it
}
#Override
protected void onDraw(Canvas canvas1) {
canvas=canvas1;
// Our move updates are calculated in ACTION_MOVE in the opposite direction
// from how we want to move the scroll rect. Think of this as dragging to
// the left being the same as sliding the scroll rect to the right.
newScrollRectX = scrollRectX - (int)scrollByX;
newScrollRectY = scrollRectY - (int)scrollByY;
// Don't scroll off the left or right edges of the bitmap.
if (newScrollRectX < 0)
newScrollRectX = 0;
else if (newScrollRectX > (floorPlan.getWidth() - displayWidth))
newScrollRectX = (floorPlan.getWidth() - displayWidth);
// Don't scroll off the top or bottom edges of the bitmap.
if (newScrollRectY < 0)
newScrollRectY = 0;
else if (newScrollRectY > (floorPlan.getHeight() - displayHeight))
newScrollRectY = (floorPlan.getHeight() - displayHeight);
// We have our updated scroll rect coordinates, set them and draw.
scrollRect.set(newScrollRectX, newScrollRectY,
newScrollRectX + displayWidth, newScrollRectY + displayHeight);
paint = new Paint();
canvas.drawBitmap(floorPlan, scrollRect, displayRect, paint);
// Update user position
if (positionX >= newScrollRectX && positionX - newScrollRectX <= displayWidth
&& positionY >= newScrollRectY && positionY - newScrollRectY <= displayHeight)
canvas.drawBitmap(userMark,positionX-newScrollRectX-userMark.getWidth()/2,positionY-newScrollRectY-userMark.getHeight()/2,paint);
class AsyncTaskToConnect extends AsyncTask <Void, Void, Void>{
#Override
protected Void doInBackground(Void... cmd) {
// connect to database and retrieve values
return null;
}
#Override
protected void onPostExecute(Void v)
{//PE
if (positionX >= newScrollRectX && positionX - newScrollRectX <= displayWidth
&& positionY >= newScrollRectY && positionY - newScrollRectY <= displayHeight)
{
canvas.drawBitmap(redPin,480-newScrollRectX-userMark.getWidth()/2,90-newScrollRectY-userMark.getHeight()/2,paint);
}
//return null;
// Reset current scroll coordinates to reflect the latest updates,
// so we can repeat this update process.
scrollRectX = newScrollRectX;
scrollRectY = newScrollRectY;
}//PE
}
AsyncTaskToConnect[] asyncTaskC = null;
asyncTaskC = new AsyncTaskToConnect[1];
asyncTaskC[0] = new AsyncTaskToConnect();
asyncTaskC[0].executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// Cache our new dimensions; we'll need them for drawing.
displayWidth = Math.min(w, floorPlan.getWidth());
displayHeight = Math.min(h, floorPlan.getHeight());
// Destination rect for our main canvas draw.
displayRect = new Rect(0, 0, displayWidth, displayHeight);
// Scroll rect: this will be used to 'scroll around' over the
// bitmap in memory.
if (positionX + displayWidth / 2 > floorPlan.getWidth())
scrollRectX = floorPlan.getWidth() - displayWidth;
else
scrollRectX = positionX - displayWidth / 2;
if (scrollRectX < 0)
scrollRectX = 0;
if (positionY + displayHeight / 2 > floorPlan.getHeight())
scrollRectY = floorPlan.getHeight() - displayHeight;
else
scrollRectY = positionY - displayHeight / 2;
if (scrollRectY < 0)
scrollRectY = 0;
scrollRect = new Rect(scrollRectX, scrollRectY, displayWidth, displayHeight);
super.onSizeChanged(w, h, oldw, oldh);
}
}
}
P.S. This is my first time posting. Please pardon me if i make mistakes in my post. Thanks.
I think the problem is that you are storing the Canvas object passed into the onDraw method. The object may not be valid after the onDraw method has returned.
It looks like you are trying to prepare a Bitmap on a background thread and then draw it on screen when it has been prepared. The way you do it is - prepare the Bitmap and just call invalidate on the View in onPostExecute method. Then in the onDraw method, you can take that Bitmap object and draw it using canvas.drawBitmap

blackberry: AbsoluteFieldManager dont show custom fields

I'm trying to make a menu with an absolute layout that contains custom items extending Field. This items show well in the HorizontalFieldManager for example, but with the AbsoluteFieldManager it just shows a blank screen.
This is my code so far:
/********************
* CustomField.java *
********************/
import net.rim.device.api.system.Bitmap;
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.Keypad;
public class CustomField extends Field {
Bitmap img;
String s1, s2;
Font font;
int textColorUnfocused, textColorFocused, bgColorUnfocused, bgColorFocused;
public CustomField(long style) {
super(style);
}
public CustomField(Bitmap img, String s1, String s2) {// , long style) {
// super(style);
this.img = img;
this.s1 = s1;
this.s2 = s2;
this.font = Font.getDefault();
textColorUnfocused = 0x000000;
textColorFocused = 0xffffff;
bgColorUnfocused = 0xffffff;
bgColorFocused = 0x3956F7;
}
protected void layout(int maxWidth, int maxHeight) {
Font font = getFont();
int width = img.getWidth() + 10;
int height = img.getHeight() + (font.getHeight() * 3);
setExtent(Math.min(width, maxWidth), Math.min(height, maxHeight));
}
protected void onFocus(int direction) {
super.onFocus(direction);
invalidate();
}
protected void onUnfocus() {
super.onUnfocus();
invalidate();
}
public boolean isFocusable() {
return true;
}
protected void paint(Graphics g) {
// Draw background
g.setColor(isFocus() ? bgColorFocused : bgColorUnfocused);
g.fillRect(0, 0, getWidth(), getHeight());
// draw image
g.drawBitmap(5, 5, img.getWidth(), img.getHeight(), img, 0, 0);
g.setColor(isFocus() ? textColorFocused : textColorUnfocused);
// draw text
g.drawText(s1, ((img.getWidth() + 10) / 2) - (font.getAdvance(s1) / 2),
img.getHeight() + font.getHeight());
g.drawText(s2, ((img.getWidth() + 10) / 2) - (font.getAdvance(s2) / 2),
img.getHeight() + (2 * font.getHeight()));
}
protected boolean keyChar(char character, int status, int time) {
if (character == Keypad.KEY_ENTER) {
fieldChangeNotify(0);
return true;
}
return super.keyChar(character, status, time);
}
public int getY() {
return img.getHeight() + (font.getHeight() * 3);
}
public int getX() {
return img.getWidth();
}
}
/**************
* MyApp.java *
**************/
import net.rim.device.api.ui.UiApplication;
public class MyApp extends UiApplication{
public static void main(String args[]){
MyApp theApp = new MyApp();
theApp.enterEventDispatcher();
}
public MyApp()
{
// Push a screen onto the UI stack for rendering.
pushScreen(new MyScreen());
}
}
/*****************
* MyScreen.java *
*****************/
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.container.AbsoluteFieldManager;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
public class MyScreen extends MainScreen {
public MyScreen() {
AbsoluteFieldManager manager = new AbsoluteFieldManager();
Bitmap img = Bitmap.getBitmapResource("1.png");
CustomField cf1 = new CustomField(img, "an", "Item");
CustomField cf2 = new CustomField(img, "another", "Item");
manager.add(cf1, 10, 10);
manager.add(cf2, 150, 150);
//HorizontalFieldManager hfm = new HorizontalFieldManager(
// Manager.HORIZONTAL_SCROLL);
//hfm.add(cf1); hfm.add(cf2);
//add(hfm);
add(manager);
}
}
And the image (1.png) http://www7.pic-upload.de/14.05.11/rhr4jcfuy9f8.png
How can I get the absolute manager to show my custom field?
My guess is that maybe AbsoluteFieldManager is passing 0, 0 to the layout method of your custom field. So your logic in there is calling setExtent(0, 0).

Add buttons to a ListField in BlackBerry

I am using a ListField in BlackBerry and want to include a button with two text fields in the row like:
Button
Text1
Text2
But I am not able to add the buttons. All the help I've found is about adding images.
Take a look at How to customize list field in blackberry and Blackberry - how to add fields to listfield
by default ... list field provides the focus on a single row as a whole....and not to the single field on a row(as u told that u want to add three fields....buttons, textfield, textfield).
so i want to know why do u want to add buttons and two separate text-fields in a single row... I think its not easy if u want to get focus only on button OR only on a text-field....in a single row of a list field.
by the way... here is the sample code........ how u create three fields in a single row of list field...
just call the constructor of this list-field class in ur main screen's class and add it like.....
DetailListField _listField = new DetailListField();
add(_listField);
DetailListField class -
class DetailListField extends ListField implements ListFieldCallback
{
private Vector rows;
private Font font;
public DetailListField()
{
this(0, ListField.USE_ALL_WIDTH | DrawStyle.LEFT);
}
public DetailListField(int numRows, long style)
{
super(0, style);
try
{
rows = new Vector();
font = Font.getDefault().derive(Font.PLAIN, 7, Ui.UNITS_pt);
setRowHeight(-2);
setCallback(this);
for (int x = 0 ; x < 5 ; x++)
{
TableRowManager row = new TableRowManager();
// button, textfield, textfield
ButtonField _btn = new ButtonField("Button", ButtonField.CONSUME_CLICK);
_btn.setBorder(VISUAL_STATE_NORMAL, BorderFactory.createSimpleBorder(new XYEdges(1,1,1,1),
new XYEdges(0x557788, 0xAA22BB, 0x557788, 0xAA22BB),
Border.STYLE_SOLID));
row.add(_btn);
BasicEditField _basicEdit1 = new BasicEditField(BasicEditField.EDITABLE | BasicEditField.FILTER_DEFAULT);
_basicEdit1.setBorder(VISUAL_STATE_NORMAL, BorderFactory.createSimpleBorder(new XYEdges(2,2,2,2),
new XYEdges(0x557788, 0xAA22BB, 0x557788, 0xAA22BB),
Border.STYLE_SOLID));
row.add(_basicEdit1);
BasicEditField _basicEdit2 = new BasicEditField(BasicEditField.EDITABLE | BasicEditField.FILTER_DEFAULT);
_basicEdit2.setBorder(VISUAL_STATE_NORMAL, BorderFactory.createSimpleBorder(new XYEdges(2,2,2,2),
new XYEdges(0x994422, 0xAA22BB, 0x994422, 0xAA22BB),
Border.STYLE_SOLID));
row.add(_basicEdit2);
// add id to the vector.
rows.addElement(row); // returnData[x][0]);
// call draw list row
// then call constructor of manager class
}
setSize(rows.size());
invalidate();
} catch(Exception e) {
}
}
public void drawListRow(ListField list, Graphics g, int index, int y, int width)
{
try
{
DetailListField dl = (DetailListField)list;
TableRowManager rowManager = (TableRowManager)dl.rows.elementAt(index);
rowManager.drawRow(g, 0, y, width, list.getRowHeight());
} catch(Exception e) {
}
}
protected boolean keyChar(char key, int status, int time)
{
if (key == Characters.ENTER)
{
return true;
// We've consumed the event.
}
else if(key == Characters.ESCAPE)
{
return true;
}
return super.keyChar(key, status, time);
}
protected boolean navigationClick(int status, int time)
{
try
{
// use below method if want to get label value from manager.
final int index = this.getSelectedIndex();
if(index >= 0) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("Selected index number : " + (index + 1));
}
});
}
} catch (final Exception e) {
}
return true;
}
public Object get(ListField listField, int index)
{
// TODO Auto-generated method stub
return rows.elementAt(index);
}
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 rows.indexOf(prefix, start);
}
/**
* MANAGER CLASS
*/
private class TableRowManager extends Manager
{
int _height = 0, _width = 0;
int yPos = 0;
public TableRowManager()
{
super(0);
}
// Causes the fields within this row manager to be layed out then
// painted.
public void drawRow(Graphics g, int x, int y, int width, int height)
{
try
{
_height = height;
_width = getPreferredWidth();
yPos = y;
// Arrange the cell fields within this row manager.
// set the size and position of each field.
layout(_width, _height);
// Place this row manager within its enclosing list.
setPosition(x, y);
// Apply a translating/clipping transformation to the graphics
// context so that this row paints in the right area.
g.pushRegion(getExtent());
// Paint this manager's controlled fields.
subpaint(g);
g.setColor(0x00CACACA);
g.drawLine(0, 0, getPreferredWidth(), 0);
// Restore the graphics context.
g.popContext();
} catch(Exception e) {
System.out.println("Exeception : (DetailListField) 4 : " + e.toString());
}
}
// Arranges this manager's controlled fields from left to right within
// the enclosing table's columns.
protected void sublayout(int width, int height)
{
try
{
// set the bitmap field
Field _field0 = getField(0);
layoutChild(_field0, (_width/3) - 30 , _height - 20);
setPositionChild(_field0, 2, 5);
// set the name field
Field _field1 = getField(1);
_field1.setFont(font);
layoutChild(_field1, (_width/3) - 30, _field1.getPreferredHeight());
setPositionChild(_field1, (_width/3) - 30 + 10, 5);
Field _field2 = getField(2);
_field2.setFont(font);
layoutChild(_field2, (_width/3) - 30, _field2.getPreferredHeight());
setPositionChild(_field2, ((_width/3) - 30)*2 + 20, 5);
setExtent(_width, _height);
} catch(Exception e) {
System.out.println("Exeception : (DetailListField) 5 : " + e.toString());
}
}
// The preferred width of a row is defined by the list renderer.
public int getPreferredWidth()
{
return (Display.getWidth());
}
// The preferred height of a row is the "row height" as defined in the
// enclosing list.
public int getPreferredHeight()
{
return _height;
}
}
}
bt still i dont know how to get focus on single field of a single row...
usage:
ListCallBack _callBack = new ListCallBack();
_countries.setCallback(_callBack);
code:
private class ListCallBack implements ListFieldCallback{
public void drawListRow(ListField listField, Graphics graphics,
int index, int y, int width) {
for(int i = 0; i <= 23; i++) {
graphics.drawBitmap(0, y, 48, 48, (Bitmap) MyApp._flagVector.elementAt(index), 0, 0);
}
String text = (String)MyApp._countryVector.elementAt(index);
graphics.drawText(text, 65, y, 0, width);
}
public Object get(ListField listField, int index) {
return MyApp._countryVector.elementAt(index);
}
public int getPreferredWidth(ListField listField) {
return Display.getWidth();
}
public int indexOfList(ListField listField, String prefix, int start) {
return MyApp._countryVector.indexOf(prefix, start);
}
}

Resources