To change the ButtonField background during click event in BlackBerry - blackberry

In BlackBerry, how to change the ButtonField background color during the click event? For example, for the long press the background color needs to change. For me it takes the default color blue. How to change it?
This is our custom buttton field. But it shows the default blue color for the button click event.
public class CustomButtonField extends ButtonField implements GlobalConstant {
int mHeight;
int mWidth;
public final static int DEFAULT_BACKGROUND_COLOR_NORMAL = 0x167c9c;
public final static int DEFAULT_BACKGROUND_COLOR_ON_FOCUS = 0x188118;
private int backgroundColorNormal = DEFAULT_BACKGROUND_COLOR_NORMAL;
private int backgroundColorOnFocus = DEFAULT_BACKGROUND_COLOR_ON_FOCUS;
private Background noraml_bg;
private Background focus_bg;
private boolean isFocusable;
private boolean isround_button = false;
public CustomButtonField(int height, int width, String label) {
super(label, CONSUME_CLICK);
noraml_bg = menuButton_bgNormal;
focus_bg = menuButton_bgFocus;
mHeight = height;
mWidth = width;
this.isFocusable = true;
setBorder(BorderFactory.createSimpleBorder(new XYEdges(0, 0, 0, 0)));
setBorder(VISUAL_STATE_ACTIVE,
BorderFactory.createSimpleBorder(new XYEdges(0, 0, 0, 0)));
}
public CustomButtonField(int height, int width, String label, boolean isround_button) {
super(label, CONSUME_CLICK);
this.isround_button = isround_button;
noraml_bg = roundButton_bgNormal;
focus_bg = roundButton_bgFocus;
mHeight = height;
mWidth = width;
this.isFocusable = true;
XYEdges padding = new XYEdges(1,1,1,1);
XYEdges color = new XYEdges (Color.BLACK,Color.BLACK,Color.BLACK,Color.BLACK);
int lineStyle = Border.STYLE_SOLID;
Border roundedBorder = BorderFactory.createSimpleBorder(padding, color, lineStyle);
setBorder(roundedBorder);
}
/*
* (non-Javadoc)
*
* #see net.rim.device.api.ui.component.ButtonField#getPreferredHeight()
*/
public int getPreferredHeight() {
return mHeight;
}
/*
* (non-Javadoc)
*
* #see net.rim.device.api.ui.component.ButtonField#getPreferredWidth()
*/
public int getPreferredWidth() {
return mWidth;
}
/*
* (non-Javadoc)
*
* #see net.rim.device.api.ui.component.ButtonField#layout(int, int)
*/
protected void layout(int width, int height) {
super.layout(mWidth, mHeight);
setExtent(mWidth, mHeight);
}
/*
* (non-Javadoc)
*
* #see
* net.rim.device.api.ui.component.ButtonField#paint(net.rim.device.api.
* ui.Graphics)
*/
protected void paint(Graphics graphics) {
String label = getLabel();
int x = (getPreferredWidth() - getFont().getAdvance(label)) >> 1;
int y = (getPreferredHeight() - getFont().getHeight()) >> 1;
if (isFocus() == false) {
this.setBackground(noraml_bg);
if(isround_button){
graphics.setColor(0x666666);
}else{
graphics.setColor(Color.WHITE);
}
graphics.drawText(label, x, y);
} else {
this.setBackground(focus_bg);
graphics.setColor(Color.WHITE);
graphics.drawText(label, x, y);
}
}
protected void drawFocus(Graphics graphics, boolean on) {
if (on) {
graphics.setColor(backgroundColorOnFocus);
} else {
graphics.setColor(backgroundColorNormal);
}
}
public boolean isFocusable() {
return isFocusable;
}
}

Using visual states indicator of the Field, and BackgroundFactory you can set Background for following visual states:
VISUAL_STATE_ACTIVE - Active visual state. The user is interacting with the field.
VISUAL_STATE_DISABLED - Disabled visual state. There is no possible interaction with the field.
VISUAL_STATE_DISABLED_FOCUS - Disabled, but focused visual state. The field is highlighted, but there is no other possible interaction with the field.
VISUAL_STATE_FOCUS - Focus visual state. The field has focus (is highlighted).
VISUAL_STATE_NORMAL - Normal visual state. There is no current interaction with the field.
Check following code snippet:
ButtonField bfTest = new ButtonField("Button Field");
Background commonBgOne = BackgroundFactory.createSolidBackground(Color.RED);
Background commonBgTwo = BackgroundFactory.createSolidBackground(Color.GREEN);
bfTest.setBackground(VISUAL_STATE_ACTIVE, commonBgOne);
bfTest.setBackground(VISUAL_STATE_DISABLED, commonBgTwo);
bfTest.setBackground(VISUAL_STATE_DISABLED_FOCUS, commonBgTwo);
bfTest.setBackground(VISUAL_STATE_FOCUS, commonBgOne);
bfTest.setBackground(VISUAL_STATE_NORMAL, commonBgTwo);
Cancelling default border
Border commonBorder = BorderFactory.createSimpleBorder(new XYEdges());
bfTest.setBorder(VISUAL_STATE_ACTIVE, commonBorder);
bfTest.setBorder(VISUAL_STATE_DISABLED, commonBorder);
bfTest.setBorder(VISUAL_STATE_DISABLED_FOCUS, commonBorder);
bfTest.setBorder(VISUAL_STATE_FOCUS, commonBorder);
bfTest.setBorder(VISUAL_STATE_NORMAL, commonBorder);

Have you tried using setBackground property of a button?

Related

ListField item background Color

I just want to know how can I change ListField's item background color. I have two items in my ListField like this one.
|First One|Second One.................|
I need to change first one's background color.
My drawListRow(..) method looks like this
public void drawListRow(ListField listField, Graphics graphics,
int index, int y, int width) {
int oldColor = 0;
try {
oldColor = graphics.getColor();
String txt = (vector.elementAt(index)).toString();
int xPos = 15;
int yPos = 5 + y;
//graphics.clear();
graphics.setColor(Color.GREEN);
graphics.fillRect(0, y, (Display.getWidth()*10/100), yPos);
graphics.drawText(txt, xPos, yPos);
//graphics.fillRect(0,(index*Display.getHeight()/10),Display.getWidth(),Display.getHeight()/10);
} finally {
graphics.setColor(oldColor);
}
}
But this is not working.
Though you have attached an image, I am still confused. The image didn't answer some question, for example, how it will look on a row get focused (I didn't understand actually).
But you can check following output and code. I think you can customize the look as you wish if you check the code.
Generated Output
How to use
public class MyScreen extends MainScreen {
private Vector listElements;
public MyScreen() {
setTitle("Custom ListField Demo");
// data for the ListField
listElements = new Vector();
for (int i = 0; i < 4; i++) {
listElements.addElement("Some text for row " + i);
}
ListField taskList = new ListField() {
// disable default focus drawing
protected void drawFocus(Graphics graphics, boolean on) {
};
};
taskList.setCallback(new ListCallback(listElements));
taskList.setSize(listElements.size());
taskList.setRowHeight(40);
add(taskList);
}
}
ListCallback implementation
class ListCallback implements ListFieldCallback {
final int COLOR_INDEX_NORMAL_BG = 0x1D6789;
final int COLOR_INDEX_FOCUSED_BG = 0x0E8CB3;
final int COLOR_NORMAL_BG = 0x2A2A2A;
final int COLOR_FOCUSED_BG = 0x1F1F1F;
private Vector listElements;
public ListCallback(Vector listElements) {
this.listElements = listElements;
}
public void drawListRow(ListField list, Graphics graphics, int index, int y,
int width) {
int rowHeight = list.getRowHeight(index);
boolean isSelectedRow = (list.getSelectedIndex() == index);
int indexBgColor = isSelectedRow ? COLOR_INDEX_FOCUSED_BG : COLOR_INDEX_NORMAL_BG;
int rowBgColor = isSelectedRow ? COLOR_FOCUSED_BG : COLOR_NORMAL_BG;
final int indexWidth = width / 10;
// draw row background
fillRectangle(graphics, rowBgColor, 0, y, width, rowHeight);
// draw index background
fillRectangle(graphics, indexBgColor, 0, y, indexWidth, rowHeight);
// set text color, draw text
Font font = list.getFont();
graphics.setColor(Color.WHITE );
graphics.setFont(font);
String indexText = "" + (index + 1);
String textToDraw = "";
try {
textToDraw = (String) listElements.elementAt(index);
} catch (Exception exc) {
}
int xText = (indexWidth - font.getAdvance(indexText)) / 2;
int yText = (rowHeight - font.getHeight()) / 2;
graphics.drawText(indexText, xText, y + yText, 0, indexWidth);
final int margin = 5;
int availableWidth = (width - indexWidth) - 2 * margin;
xText = indexWidth + margin;
yText = (rowHeight - font.getHeight()) / 2;
graphics.drawText(textToDraw, xText, y + yText, DrawStyle.ELLIPSIS, availableWidth);
}
private void fillRectangle(Graphics graphics, int color, int x, int y, int width, int height) {
graphics.setColor(color);
graphics.fillRect(x, y, width, height);
}
public Object get(ListField list, int index) {
// not implemented
return "";
}
public int indexOfList(ListField list, String prefix, int string) {
// not implemented
return 0;
}
public int getPreferredWidth(ListField list) {
return Display.getWidth();
}
}
If you need to change onFocus Background color than add drwFocus method on your ListField.
protected void drawFocus(Graphics graphics, boolean on) {
//get the focus rect area
XYRect focusRect = new XYRect();
getFocusRect(focusRect);
boolean oldDrawStyleFocus = graphics.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS);
try {
if (on) {
//set the style so the fields in the row will update its color accordingly
graphics.setDrawingStyle(Graphics.DRAWSTYLE_FOCUS, true);
int oldColour = graphics.getColor();
try {
graphics.setColor(0xc8d3db); //set the color and draw the color
graphics.fillRect(focusRect.x, focusRect.y,
focusRect.width, focusRect.height);
} finally {
graphics.setColor(oldColour);
}
//to draw the row again
drawListRow(this, graphics, getSelectedIndex(),
focusRect.y, focusRect.width);
// drawRow(graphics, focusRect.x,focusRect.y, focusRect.width,focusRect.height);
}
} finally {
graphics.setDrawingStyle(Graphics.DRAWSTYLE_FOCUS, oldDrawStyleFocus);
}
}
Check the edited answer,
protected void drawFocus(Graphics graphics, boolean on) {
XYRect focusRect = new XYRect();
getFocusRect(focusRect);
boolean oldDrawStyleFocus = graphics.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS);
try {
if (on) {
graphics.setDrawingStyle(Graphics.DRAWSTYLE_FOCUS, true);
int oldColour = Color.BLACK;
try {
graphics.fillRect(focusRect.x, focusRect.y,
focusRect.width, focusRect.height);
} finally {
graphics.setColor(oldColour);
}
//to draw the row again
drawListRow(this, graphics, getSelectedIndex(),
focusRect.y, focusRect.width);
}
} finally {
graphics.setDrawingStyle(Graphics.DRAWSTYLE_FOCUS, oldDrawStyleFocus);
}
}

Vertical Scroll TextField in Blackberry

I am new to Blackberry developement.I want do the custom textfield in my application.
I write a code for that But I want to scroll the text in that text field (if me text in textfield extends above 4 line.)
I use manager class to add vertical scroll but cant get it.
TextField textfield1=new TextField(Manager.VERTICAL_SCROLL);
Anybody know how to give vertical scroll to the text field.
Try the following code:
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.component.TextField;
import net.rim.device.api.ui.container.VerticalFieldManager;
public class MyTextField extends VerticalFieldManager {
private int fieldWidth;
private int fieldHeight;
private TextField textField;
public MyTextField(int width, int height) {
super(Manager.NO_VERTICAL_SCROLL);
fieldWidth = width;
fieldHeight = height;
VerticalFieldManager vfm = new VerticalFieldManager(Manager.VERTICAL_SCROLL|Manager.VERTICAL_SCROLLBAR);
textField = new TextField() {
public void paint(Graphics g) {
getManager().invalidate();
super.paint(g);
}
};
vfm.add(textField);
add(vfm);
}
public void paint(Graphics g) {
// draw the border of the text area;
int color = g.getColor();
g.setColor(0x00FFCC);
g.drawRect(0, 0, fieldWidth, fieldHeight);
g.setColor(color);
super.paint(g);
}
public void sublayout(int width, int height) {
if (fieldWidth == 0) {
fieldWidth = width;
}
if (fieldHeight == 0) {
fieldHeight = height;
}
super.sublayout(fieldWidth, fieldHeight);
setExtent(fieldWidth,fieldHeight);
}
public String getText() {
return textField.getText();
}
public void setText(String text) {
textField.setText(text);
}
}
add it to your Screen or Manager by specifying the size like this:
add(new MyTextField(200, 200));
Create
HorizontalFieldManager HorizontalFieldManager=new HorizontalFieldManager(Manager.VERTICAL_SCROLL);
Then
TextField textfield1=new TextField();
HorizontalFieldManager.add(textfield1);
add(HorizontalFieldManager);
you can use custom textbox as bellow.
public class CustomTextBox extends Manager
{
/**
* Default margins
*/
private final static int DEFAULT_LEFT_MARGIN = 10;
private final static int DEFAULT_RIGHT_MARGIN = 10;
private final static int DEFAULT_TOP_MARGIN = 5;
private final static int DEFAULT_BOTTOM_MARGIN = 5;
/**
* Default paddings
*/
private final static int DEFAULT_LEFT_PADDING = 10;
private final static int DEFAULT_RIGHT_PADDING = 10;
private final static int DEFAULT_TOP_PADDING = 5;
private final static int DEFAULT_BOTTOM_PADDING = 5;
/**
* Margins around the text box
*/
private int topMargin = DEFAULT_TOP_MARGIN;
private int bottomMargin = DEFAULT_BOTTOM_MARGIN;
private int leftMargin = DEFAULT_LEFT_MARGIN;
private int rightMargin = DEFAULT_RIGHT_MARGIN;
/**
* Padding around the text box
*/
private int topPadding = DEFAULT_TOP_PADDING;
private int bottomPadding = DEFAULT_BOTTOM_PADDING;
private int leftPadding = DEFAULT_LEFT_PADDING;
private int rightPadding = DEFAULT_RIGHT_PADDING;
/**
* Amount of empty space horizontally around the text box
*/
private int totalHorizontalEmptySpace = leftMargin + leftPadding
+ rightPadding + rightMargin;
/**
* Amount of empty space vertically around the text box
*/
private int totalVerticalEmptySpace = topMargin + topPadding
+ bottomPadding + bottomMargin;
/**
* Minimum height of the text box required to display the text entered
*/
private int minHeight = getFont().getHeight() + totalVerticalEmptySpace;
/**
* Width of the text box
*/
private int width = Display.getWidth();
/**
* Height of the text box
*/
private int height = minHeight;
/**
* Background image for the text box
*/
private EncodedImage backgroundImage;
/**
* Bitmap version of the backgroundImage.
* Needed to reduce the calculation overhead incurred by
* scaling of the given image
* and derivation of Bitmap from the
* EncodedImage every time it is needed.
*/
private Bitmap bitmapBackgroundImage;
/**
* The core element of this text box
*/
private EditField editField;
//private BasicEditField editField;
//private String entireText;
public CustomTextBox()
{
// Let the super class initialize the core
super(0);
// An edit field is the sole field of this manager.
editField = new EditField();
//editField = new CustomEditField();
add(editField);
}
public CustomTextBox(EncodedImage backgroundImage)
{
this();
setBackgroundImage(backgroundImage);
}
public void setSize(int width, int height)
{
boolean isChanged = false;
if (width > 0 // Ignore invalid width
&& this.width != width)
{
this.width = width;
isChanged = true;
}
// Ignore the specified height if it is less
// than the minimum height required to display the text.
if (height > minHeight && height != this.height)
{
this.height = height;
isChanged = true;
}
// If width/height has been changed and background image
// is available, adapt it to the new dimension
if (isChanged == true && backgroundImage != null)
{
bitmapBackgroundImage = getScaledBitmapImage(backgroundImage,
this.width - (leftMargin+rightMargin),
this.height - (topMargin+bottomMargin));
}
}
public void setWidth(int width)
{
if (width > 0 && width != this.width)
{
this.width = width;
// If background image is available, adapt it to the new width
if (backgroundImage != null)
{
bitmapBackgroundImage = getScaledBitmapImage(backgroundImage,
this.width - (leftMargin+rightMargin),
this.height - (topMargin+bottomMargin));
}
}
}
public void setHeight(int height)
{
// Ignore the specified height if it is
// less than the minimum height required to display the text.
if (height > minHeight)
{
this.height = height;
// If background image is available, adapt it to the new width
if (backgroundImage != null)
{
bitmapBackgroundImage = getScaledBitmapImage(backgroundImage,
this.width - (leftMargin+rightMargin),
this.height - (topMargin+bottomMargin));
}
}
}
public void setBackgroundImage(EncodedImage backgroundImage)
{
this.backgroundImage = backgroundImage;
// Consider the height of background image in
// calculating the height of the text box.
// setHeight() does not ensure that specified
// height will be in effect, of course, for valid reasons.
// So derivation of Bitmap image in the setHeight() method is not sure.
setHeight(backgroundImage.getHeight() + topMargin + bottomMargin);
if (bitmapBackgroundImage == null)
{
bitmapBackgroundImage = getScaledBitmapImage(backgroundImage,
this.width - (leftMargin+rightMargin),
this.height - (topMargin+bottomMargin));
}
}
/**
* Generate and return a Bitmap Image scaled according
* to the specified width and height.
*
* #param image EncodedImage object
* #param width Intended width of the returned Bitmap object
* #param height Intended height of the returned Bitmap object
* #return Bitmap object
*/
private Bitmap getScaledBitmapImage(EncodedImage image, int width, int height)
{
// Handle null image
if (image == null)
{
return null;
}
int currentWidthFixed32 = Fixed32.toFP(image.getWidth());
int currentHeightFixed32 = Fixed32.toFP(image.getHeight());
int requiredWidthFixed32 = Fixed32.toFP(width);
int requiredHeightFixed32 = Fixed32.toFP(height);
int scaleXFixed32 = Fixed32.div(currentWidthFixed32, requiredWidthFixed32);
int scaleYFixed32 = Fixed32.div(currentHeightFixed32, requiredHeightFixed32);
image = image.scaleImage32(scaleXFixed32, scaleYFixed32);
return image.getBitmap();
}
protected void sublayout(int width, int height)
{
// We have one and only child - the edit field.
// Place it at the appropriate place.
Field field = getField(0);
layoutChild(field, this.width - totalHorizontalEmptySpace,
this.height - totalVerticalEmptySpace);
setPositionChild(field, leftMargin+leftPadding, topMargin+topPadding);
setExtent(this.width, this.height);
}
public void setTopMargin(int topMargin)
{
this.topMargin = topMargin;
}
public void setBottomMargin(int bottomMargin)
{
this.bottomMargin = bottomMargin;
}
protected void paint(Graphics graphics)
{
// Draw background image if available, otherwise draw a rectangle
if (bitmapBackgroundImage == null)
{
graphics.drawRect(leftMargin, topMargin,
// width - (leftMargin+rightMargin),
// height - (topMargin+bottomMargin));
graphics.drawRoundRect(leftMargin, topMargin,
width - (leftMargin+rightMargin),
height - (topMargin+bottomMargin), 5, 5);
}
else
{
graphics.drawBitmap(leftMargin, topMargin,
width - (leftMargin+rightMargin),
height - (topMargin+bottomMargin),
bitmapBackgroundImage, 0, 0);
}
// Determine the rightward text that can fit into the visible edit field
EditField ef = (EditField)getField(0);
String entireText = ef.getText();
boolean longText = false;
String textToDraw = "";
Font font = getFont();
int availableWidth = width - totalHorizontalEmptySpace;
if (font.getAdvance(entireText) <= availableWidth)
{
textToDraw = entireText;
}
else
{
int endIndex = entireText.length();
for (int beginIndex = 1; beginIndex < endIndex; beginIndex++)
{
textToDraw = entireText.substring(beginIndex);
if (font.getAdvance(textToDraw) <= availableWidth)
{
longText = true;
break;
}
}
}
if (longText == true)
{
// Force the edit field display only the truncated text
ef.setText(textToDraw);
// Now let the components draw themselves
super.paint(graphics);
// Return the text field its original text
ef.setText(entireText);
}
else
{
super.paint(graphics);
}
}
public int getPreferredWidth()
{
return width;
}
public int getPreferredHeight()
{
return height;
}
protected boolean keyChar(char ch, int status, int time)
{
if (ch == Characters.ENTER)
{
return true;
}
else
{
return super.keyChar(ch, status, time);
}
}
public String getText()
{
return ((EditField)getField(0)).getText();
}
public void setText(final String text)
{
((EditField)getField(0)).setText(text);
}
}

Refreshing field's state

In my application I'm using custom fields, with "set***" methods wich changes some parameters of this fields (background image, for example). thay work allmost fine, only one problem: I'm setting and changing parameters of this fields like below:
record = new UIButton("RECORD", Field.FOCUSABLE, kButtonWidth/3-5, kButtonHeight);
vfm2.add(Record); //I tryed this befor setters and after: no different
record.setBackgroundImage("buttonDark.png", "buttonDark.png", "buttonDark.png");
record.setTitleFontSize(Display.getHeight()/40);
record.setTitle("RECORD");
When the screen with this fields are pushed, my field looks like no setters were called (but it was: I checked this via log messages). Field's state refreshes only after it is focused (I'm calling same setters on onFocus and on onUnFocus, where I have invalidate()). Is there any way to refrash it on screen appear? In iPhone SDK, for example, there is viewDidAppear method, that colled when view(screen) did appear. Is there any same in blackberry? Or any other solution?
Here is my code of UIButton class:
public class UIButton extends Field
{
private String title = null;
private Font font;
private int fontSize;
private int color;
private int horizontalAligment;
private int state; //0 - normal; 1 - focused; 2 - HightLighted;
private int height;
private int width;
private EncodedImage currentPicture;
private EncodedImage onPicture;
private EncodedImage offPicture;
private EncodedImage lightPicture;
public UIButton(long style, int Widgh, int Height)
{
super(style);
height = Height;
width = Widgh;
fontSize = Display.getHeight()/20;
FontFamily ff = getFont().getFontFamily();
font = ff.getFont(0, fontSize);
title = "";
color = Color.WHITE;
state = 0;
horizontalAligment = DrawStyle.HCENTER;
onPicture = offPicture = lightPicture = EncodedImage.getEncodedImageResource("buttonDark.png");
currentPicture = offPicture;
}
public String getTitle()
{
return title;
}
public void setTitleColor (int Color) {
color = Color;
invalidate();
}
public void setFrame (int Height, int Width) {
height = Height;
width = Width;
invalidate();
}
public void setTitle (String Title) {
title = Title;
invalidate();
}
public void setTitleHorizontalAligment (int hAligment) {
horizontalAligment = hAligment;
invalidate();
}
public void setBackgroundImage (String forStateNurmal, String forStateFocused, String forStateHightlighted) {
onPicture = EncodedImage.getEncodedImageResource(forStateFocused);
offPicture = EncodedImage.getEncodedImageResource(forStateNurmal);
lightPicture = EncodedImage.getEncodedImageResource(forStateHightlighted);
invalidate();
}
public void setState (int State) {
state = State;
switch (state) {
case 0: {
currentPicture = offPicture;
invalidate();
break;
}
case 1: {
currentPicture = onPicture;
invalidate();
break;
}
case 2: {
currentPicture = lightPicture;
invalidate();
break;
}
}
}
public void setTitleFont (Font Font) {
font = Font;
invalidate();
}
public void setTitleFontSize (int FontSize) {
fontSize = FontSize;
FontFamily ff = font.getFontFamily();
font = ff.getFont(0, fontSize);
invalidate();
}
public int getPreferredHeight()
{
return height;
}
public int getPreferredWidth()
{
return width;
}
protected void onFocus(int direction)
{
super.onFocus(direction);
this.setState(0);
}
protected void onUnfocus()
{
if (state!=2) this.setState(1);
}
protected void drawFocus(Graphics graphics, boolean on)
{
super.drawFocus(graphics, on);
}
protected void layout(int width, int height)
{
setExtent(getPreferredWidth(),getPreferredHeight());
}
protected void paint(Graphics graphics)
{
ResizeImage r = new ResizeImage();
currentPicture = r.sizeImage(currentPicture, width-2, height-2);
graphics.drawBitmap(1, 1, width-2, height-2, currentPicture.getBitmap(), 0, 0);
if (title.getBytes().length>0) {
graphics.setColor(color);
graphics.setFont(font);
int x = 0;
if (horizontalAligment == DrawStyle.LEFT) x = 2;
graphics.drawText(title, x, (height-font.getHeight())/2,
(int)( getStyle() & DrawStyle.VCENTER & horizontalAligment | DrawStyle.HALIGN_MASK ), width );
}
}
protected boolean navigationClick(int status, int time)
{
fieldChangeNotify(1);
return true;
}
}
It is a very strong convention in Java to name local and field identifiers with lower case letters. So seeing "Record" as a local variable name is quite confusing.
Without the code for your custom field, UIButton, it is impossible to answer your question here. Built-in components for BlackBerry OS would behave correctly given this sequence of add and sets, so it is likely your custom field isn't following the BlackBerry conventions with layout and painting.
You forgot to change currentPicture in setBackgroundImage(). Try currentPicture = offPicture
or call this.setState(0) in setBackgroundImage().
If you call the set** methods before you add the field to the manager you should not have this problem in the first place. Is there a reason you call them after?

How to change the color of the button on clicking it

I have a button field. its color is red. when i click on it color the button should change to black how to do it?
If your button is an a class="button" tag, you can do it like this:
a.button {
color: black;
}
You can try with "Tutorial: Creating a custom button" of the official RIM docs.
I think it is what your looking for
Have you tried out this tutorial "Blackberry Custom Button Field" or you can also make a Bitmap Field with the background set to one color and have a custom paint method implemented for the required changes.
try this it is work,
public int checkBoxFlag1 = 0;
public int checkBoxFlag2 = 0;
public int checkBoxFlag3 = 0;
final Bitmap focuscheckButton = Bitmap.getBitmapResource("checkbox_tickmark.png");
final Bitmap unfocuscheckButton = Bitmap.getBitmapResource("checkbox.png");
HorizontalFieldManager checkBoxFieldManager = new HorizontalFieldManager();
BitmapField checkBox1 = new BitmapField(unfocuscheckButton,Field.FOCUSABLE)
{
protected void paint(Graphics graphics)
{
// TODO Auto-generated method stub
if(checkBoxFlag1==0)
{
this.setBitmap(unfocuscheckButton);
}
else
{
this.setBitmap(focuscheckButton);
}
super.paint(graphics);
}
protected boolean navigationClick(int status, int time)
{
// TODO Auto-generated method stub
if(checkBoxFlag1==0)
{
checkBoxFlag1=1;
}
else
{
checkBoxFlag1=0;
}
return super.navigationClick(status, time);
}
};
checkBox1.setMargin(0,20,0,20);
checkBoxFieldManager.add(checkBox1);
use this -
image1 is red color image button and image2 is black
reg_can_btn editprofile = new reg_can_btn("", Field.FOCUSABLE |FIELD_HCENTER, image1, image2, 0x102839);
then
public class edit_profile_btn extends Field {
private String _label;
private int _labelHeight;
private int _labelWidth;
private Font _font;
private Bitmap _currentPicture;
private Bitmap _onPicture;
private Bitmap _offPicture;
int color;
public edit_profile_btn(String text, long style ,String img, String img_hvr, int color){
super(style);
_offPicture = Bitmap.getBitmapResource(img);
_onPicture = Bitmap.getBitmapResource(img_hvr);
_font = getFont();
_label = text;
_labelHeight = _onPicture.getHeight();
_labelWidth = _onPicture.getWidth();
this.color = color;
_currentPicture = _offPicture;
}
/**
* #return The text on the button
*/
String getText(){
return _label;
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#getPreferredHeight()
*/
public int getPreferredHeight(){
return _labelHeight;
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#getPreferredWidth()
*/
public int getPreferredWidth(){
return _labelWidth;
}
/**
* Field implementation. Changes the picture when focus is gained.
* #see net.rim.device.api.ui.Field#onFocus(int)
*/
protected void onFocus(int direction) {
_currentPicture = _onPicture;
invalidate();
}
/**
* Field implementation. Changes picture back when focus is lost.
* #see net.rim.device.api.ui.Field#onUnfocus()
*/
protected void onUnfocus() {
_currentPicture = _offPicture;
invalidate();
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#drawFocus(Graphics, boolean)
*/
protected void drawFocus(Graphics graphics, boolean on) {
// Do nothing
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#layout(int, int)
*/
protected void layout(int width, int height) {
setExtent(Math.min( width, getPreferredWidth()),
Math.min( height, getPreferredHeight()));
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#paint(Graphics)
*/
protected void paint(Graphics graphics){
// First draw the background colour and picture
//graphics.setColor(this.color);
graphics.setBackgroundColor(Color.BLACK);
graphics.fillRect(0, 0, getWidth(), getHeight());
graphics.drawBitmap(0, 0, getWidth(), getHeight(), _currentPicture, 0, 0);
// Then draw the text
graphics.setColor(Color.BLACK);
graphics.setFont(_font);
graphics.drawText(_label, 4, 2,
(int)( getStyle() & DrawStyle.ELLIPSIS | DrawStyle.HALIGN_MASK ),
getWidth() - 6 );
}
/**
* Overridden so that the Event Dispatch thread can catch this event
* instead of having it be caught here..
* #see net.rim.device.api.ui.Field#navigationClick(int, int)
*/
protected boolean navigationClick(int status, int time){
fieldChangeNotify(1);
return true;
}
}

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