How to display buttons with background in whole width and height blackberry? - blackberry

I am displaying buttons dynamically in my app. When I am determining the number of buttons to be displayed it works fine. However, now I want to change the background color of the button on click and I am able to do that too, but only the label portion changed its color and the rest all is still the same.
So, how can I solve this problem? Here is the code I have so far:
btn = new ButtonField[Global.vec_locdisablecityname.size()];
for(int i=0;i<Global.vec_locdisablecityname.size();i++){
btn[i] = new ButtonField("",ButtonField.CONSUME_CLICK |ButtonField.FOCUSABLE);
btn[i].setLabel((String)Global.vec_locdisablecityname.elementAt(i));
if(Global.flag == true){
Global.flag = false;
Bitmap bmp_backbtnclick=Bitmap.getBitmapResource("bg-btn-location.png");
Background bg_backbtnclick=BackgroundFactory.createBitmapBackground(bmp_backbtnclick);
btn[i].setBackground(bg_backbtnclick);
}
else {
if(Global.selectedbutton == i){
Bitmap bmp_backbtnclick=Bitmap.getBitmapResource("bg-btn-location.png");
Background bg_backbtnclick=BackgroundFactory.createBitmapBackground(bmp_backbtnclick);
btn[i].setBackground(bg_backbtnclick);
}
else {
btn[i].setBackground(null);
}
}
FieldChangeListener listener = new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if ( field instanceof ButtonField ) {
for ( int i = 0; i <= 1; i++ ) {
if ( field == btn[i] ) {
System.out.println("CLicked::::---->>>" +i);
btn[i].setBackground(null);
Global.selectedbutton = i;
selectedcityid = Global.vec_locdisablecitycode.elementAt(i).toString();
System.out.println("value of selected city id:::-->>" +selectedcityid);
selectedcitycodeparse(selectedcityid);
selectedstartloading();
break;
}
else {
btn[i].setBackground(null);
}
}
}
}
};
btn[i].setChangeListener(listener);
hfmbuttons.add(btn[i]);
}

Related

XNA Touch Location

I am making a bubble wrap game. The kind where you press the bubbles to pop them and they unpop after a little bit. it all works fine, the bubbles pop and unpop as planned. There is one issue though. Whenever I click and drag the bubbles still pop. Is there a way to get them not to pop when i click and drag? Here is my code for the touch location.
foreach (TouchLocation tl in touches)
{
if (tl.State == TouchLocationState.Pressed)
{
if (rectangle.Contains((int)tl.Position.X, (int)tl.Position.Y))
{
popLocationX = (int)tl.Position.X;
popLocationY = (int)tl.Position.Y;
}
}
}
Here is what I do, I use this on my main menu but should be able to transfer over.
Have these added in:
MouseState mouse;
public float mouseDelay = 0.01f;
public float mouseTime = 0.0f;
public bool mouseActive = true;
public bool mouseUsed = false;
public string mouseOn = "None";
public Vector2 mouseLocation;
mouse helps find the location of the mouse.
mouseDelay will stop the the repeating when you have the mouse in the pressed position.
mouseTime will say hey, if I am greater than mouseDelay mouse can be used again.
mouseActive will say if it is pressed or not. If mouse is pressed mouseActive is false.
mouseUsed will see if it is ever used. If the mouse is not clicking on anything but the background then it will be false. If true that means it was used to do something.
mouseOn is used in my main menu to say you pressing on options? Make mouseOn = "Options";and go to it.
The mouseLocation holds where the mouse is.
All this in mind putting this all together will help you with your goal of not having the mouse used when it is already pressed.
In update:
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
mouse = Mouse.GetState();
if (this.IsMouseVisible == true)
{
MouseActive(gameTime);
}
base.Update(gameTime);
}
I have if mouse is visible to stop the process from repeating when the mouse is not there (less processing power).
Remember this was made for a main menu if you want to make this for a game you need to mess around with it a little.
void MouseActive(GameTime gameTime)
{
mouseTime += (float)gameTime.ElapsedGameTime.TotalSeconds;
mouse = Mouse.GetState();
mouseLocation = new Vector2(mouse.X, mouse.Y);
switch (gameState)
{
case GameStates.TitleScreen:
break;
case GameStates.Options:
break;
case GameStates.Credits:
break;
}
if (mouseOn != "None")
{
mouseUsed = true;
switch (gameState)
{
case GameStates.TitleScreen:
if (mouseOn == "Play")
{
}
if (mouseOn == "Quit")
this.Exit();
if (mouseOn == "Options")
gameState = GameStates.Options;
if (mouseOn == "Title")
{
}
break;
case GameStates.Options:
break;
case GameStates.Credits:
break;
}
mouseOn = "None";
}
if (mouse.LeftButton == ButtonState.Pressed)
{
mouseTime = 0.0f;
mouseActive = false;
}
if (mouse.LeftButton == ButtonState.Released && mouseTime > mouseDelay)
{
mouseActive = true;
mouseUsed = false;
}
}
All the code from above is going to be in the main class
Here is a class named TitleScreen.cs were I use the images on the TitlesScreen and the mouse from the main class:
You first need to Initialize the thing so add this method in TitleScreen:
Game1 game1;
public void Initialize(Game1 game1)
{
this.game1 = game1;
}
You need to add in an Initializer to the Main class(Game1.cs)
TitleScreen titlescreen;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
titlescreen = new TitleScreen();
}
protected override void Initialize()
{
titlescreen.Initialize(this);
base.Initialize();
}
Then for the final step you add Update to the TitleScreen:
public void Update(GameTime gameTime)
{
MouseState mouse = Mouse.GetState();
if (mouse.LeftButton == ButtonState.Pressed && game1.mouseUsed == false && game1.mouseActive == true)
{
if (play.Contains(mouse.X, mouse.Y))
{
game1.mouseOn = "Play";
game1.mouseUsed = true;
}
else if (title.Contains(mouse.X, mouse.Y))
{
game1.mouseOn = "Title";
game1.mouseUsed = true;
}
else if (options.Contains(mouse.X, mouse.Y))
{
game1.mouseOn = "Options";
game1.mouseUsed = true;
}
else if (quit.Contains(mouse.X, mouse.Y))
{
game1.mouseOn = "Quit";
game1.mouseUsed = true;
}
}
}
You also need to add this to the Update in the main class
titlescreen.Update(gameTime);
I've not worked with touch yet, but the logic should be similar across all input methods.
I would create a variable to store the old TouchLocationState. That way, you can check if the user is clicking and dragging. For example:
//TODO: instantiate this
TouchLocationState oldTLState;
...
// This condition will only be true when the user clicks once, dragging will return false as the oldTLSTate is not released
if (tl.State == TouchLocationState.Pressed && oldTLState.State == TouchLocationState.Released)
{
if (rectangle.Contains((int)tl.Position.X, (int)tl.Position.Y))
{
popLocationX = (int)tl.Position.X;
popLocationY = (int)tl.Position.Y;
}
}
//At the end of the Update() method, update oldTLState with the current state
oldTLState = tl;

Blackberry verticalfieldmanager partial screen scrolling with label fields

I am trying to create a set of FAQ questions and answers using a bunch of LabelFields in a VFM. Issue is that when I try to scroll, it jumps to the bottom of the list and doesn't show the mid-section questions.
public class HelpTab implements ITabAreaLayout, ScrollChangeListener {
public String[] GetQandAs() {
String[] QandAs = new String[22];
QandAs[0] = "Q. ....";
QandAs[1] = "A. ....";
....
....
QandAs[20] = "Q. ...";
QandAs[21] = "A. ....";
return QandAs;
}
VerticalFieldManager _vfm;
public VerticalFieldManager GetLayout() {
_vfm = new VerticalFieldManager(Field.FIELD_LEFT
| Manager.VERTICAL_SCROLL | Manager.VERTICAL_SCROLLBAR);
_vfm.add(UIElements.GetTitleArea(" ? FAQ"));
String[] QandAs = GetQandAs();
for (int i = 0; i < QandAs.length; i++) {
LabelField lblQandA = null;
if ((i % 2) == 0) {
lblQandA = UIElements.GetQuestionLabel(QandAs[i]);
} else {
lblQandA = UIElements.GetAnswerLabel(QandAs[i]);
}
_vfm.add(lblQandA);
}
_vfm.add(new NullField(NullField.FOCUSABLE)); // for scrolling
return _vfm;
}
public void scrollChanged(Manager manager, int newHorizontalScroll,
int newVerticalScroll) {
if (_vfm != null){
_vfm.setVerticalScroll(newVerticalScroll);
}
}
public class HomeScreen extends MainScreen
{
public HomeScreen() {
super(Manager.FIELD_HCENTER | Screen.NO_VERTICAL_SCROLL);
_vfmMain = new VerticalFieldManager();
// add header image
_vfmMain.add(UIElements
.GetBitmapField(UIElements.IMG_HEADER, false));
// add tab strip
_vfmMain.add(MakeTabStrip());
add(_vfmMain);
_vfmTabArea = new HelpTab().GetLayout();
add(_vfmTabArea);
}
}
I was not able to find much help on setVerticalScroll usage, maybe that is the reason for this issue.
Please advise.
Thanks
In your code, you added the focusable null field at the end position of the loop. so if you scroll, it will goto the last element. If you add the focusable field to- After first question, then after second question, ..... so it will scroll one by one.
Try This code -
for (int i = 0; i < QandAs.length; i++) {
LabelField lblQandA = null;
if ((i % 2) == 0) {
lblQandA = UIElements.GetQuestionLabel(QandAs[i]);
} else {
lblQandA = UIElements.GetAnswerLabel(QandAs[i]);
}
_vfm.add(lblQandA);
_vfm.add(new NullField(NullField.FOCUSABLE)); //after each element, add a focusable null field.
}
As Signare has pointed out, the issue here is probably related to your LabelFields not being focusable, which are they are not by default. One answer is to add NullFields as has been suggested. However I suspect you actually want these to be focusable, so the user can click on the one they would like more information on. So make your LabelFields Focusable, by setting the style, for example
LabelField lab = new LabelField("Label", LabelField.FOCUSABLE);
Alternatively, and to my mind preferably, use RichTextField instead of LabelField. This will give you scrolling line by line, LabelField focuses on the whole text.

To attach a ButtonField on every row of CustomListField in BlackBerry [duplicate]

i m writing one application in which i have created custom list field for displaying listview.
my CustomListField contains one image and text in a row. i m gettiing field change listener on click of listfield row but i want to put fieldchange listener on image too..
can anyone tell me how can i do that.
here is my code.
public class CustomListField extends ListField implements ListFieldCallback {
private Vector _listData;
private int _MAX_ROW_HEIGHT = 60;
public CustomListField(Vector data) {
_listData = data;
setSize(_listData.size());
setSearchable(true);
setCallback(this);
setRowHeight(_MAX_ROW_HEIGHT);
}
protected void drawFocus(Graphics graphics, boolean on) {
XYRect rect = new XYRect();
graphics.setGlobalAlpha(150);
graphics.setColor(Color.BLUE);
getFocusRect(rect);
drawHighlightRegion(graphics, HIGHLIGHT_FOCUS, true, rect.x, rect.y, rect.width, rect.height);
}
public int moveFocus(int amount, int status, int time) {
this.invalidate(this.getSelectedIndex());
return super.moveFocus(amount, status, time);
}
public void onFocus(int direction) {
super.onFocus(direction);
}
protected void onUnFocus() {
this.invalidate(this.getSelectedIndex());
}
public void refresh() {
this.getManager().invalidate();
}
public void drawListRow(ListField listField, Graphics graphics, int index, int y, int w) {
listField.setBackground(BackgroundFactory.createBitmapBackground(Bitmap.getBitmapResource("listing_bg.png")));
ListRander listRander = (ListRander) _listData.elementAt(index);
graphics.setGlobalAlpha(255);
graphics.setFont(Font.getDefault().getFontFamily().getFont(Font.PLAIN, 24));
final int margin = 5;
final Bitmap thumb = listRander.getListThumb();
final String listHeading = listRander.getListTitle();
final Bitmap nevBar = listRander.getNavBar();
// list border
graphics.setColor(Color.GRAY);
graphics.drawRect(0, y, w, _MAX_ROW_HEIGHT);
// thumbnail border & thumbnail image
graphics.setColor(Color.BLACK);
// graphics.drawRoundRect(margin-2, y+margin-2,thumb.getWidth()+2, thumb.getHeight()+2, 5, 5);
graphics.drawBitmap(margin, y + margin, thumb.getWidth(), thumb.getHeight(), thumb, 0, 0);
// drawing texts
// graphics.setFont(Font.BOLD);
graphics.drawText(listHeading, margin + thumb.getWidth(), y + margin);
graphics.setColor(Color.GRAY);
// graphics.setFont(Font.smallFont); // graphics.drawText(listDesc, 2*margin+thumb.getWidth(), y+ margin+20); // //
// graphics.drawText(listDesc2, 2*margin+thumb.getWidth(), y+ margin+32);
// draw navigation button
final int navBarPosY = y + (_MAX_ROW_HEIGHT / 2 - nevBar.getHeight() / 2);
final int navBarPosX = Graphics.getScreenWidth() - nevBar.getWidth() + margin;
graphics.drawBitmap(navBarPosX, navBarPosY, nevBar.getWidth(), nevBar.getHeight(), nevBar, 0, 0);
}
public Object get(ListField listField, int index) {
String rowString = (String) _listData.elementAt(index);
return rowString;
}
public int indexOfList(ListField listField, String prefix, int start) {
for (Enumeration e = _listData.elements(); e.hasMoreElements();) {
String rowString = (String) e.nextElement();
if (rowString.startsWith(prefix)) {
return _listData.indexOf(rowString);
}
}
return 0;
}
public int getPreferredWidth(ListField listField) {
return 3 * listField.getRowHeight();
}
/*
protected boolean trackwheelClick(int status, int time) {
invalidate(getSelectedIndex());
Dialog.alert(" U have selected :" + getSelectedIndex());
return super.trackwheelClick(status, time);
}
*/
}
i want to put click listner on star image of listfield row
and following is output of abbove code.
I did something very similar to this on a past project:
Background
As Arhimed said in his answer, and as you can read about on the BlackBerry forums here, you can't have full-fledged Field objects within the ListField. The content of ListField rows is just drawn directly in drawListRow() as text, and Bitmaps, etc. The contents aren't Field instances, and therefore, are not focusable.
So, what I did was to replace ListField with a subclass of Manager. Originally, I used a VerticalFieldManager, but I ran into problems with that. I've also been seeing a lot of issues on stack overflow, where people subclass VerticalFieldManager, customize just one small behaviour, and everything starts breaking. It seems to me that VerticalFieldManager works well if you accept its normal behaviour, and if you need something more, just extend Manager directly. Performing layout for vertically stacked rows is pretty easy.
I then made each row its own Manager, and implemented custom layout in sublayout() to place the row's Fields where I wanted them. I could then also make the row focusable, and then a bitmap/button on the row separately focusable (like your star). Clicking the row invokes one action, and clicking the star invokes another one.
I will note, however, that in my app, performance was not an issue, because I only had 10-20 rows. Also, I did have to modify my code to match your example, so consider this code only lightly tested. However, I did build it into an app, so it should perform fine as long as my assumptions, and your description were valid.
Implementation
First, it wasn't clear to me what your ListRander is (you didn't show that code). However, in my code, I need a data class to contain details about one row. It looked like that's how you used ListRander, so that's what I used:
public class ListRander {
private String _title;
private Bitmap _thumb;
public ListRander(String title, Bitmap thumb) {
_title = title;
_thumb = thumb;
}
public String getTitle() {
return _title;
}
public Bitmap getThumb() {
return _thumb;
}
}
Then, I replaced your CustomListField class with my own:
public class CustomListField extends Manager implements FocusChangeListener {
private int _MAX_ROW_HEIGHT = 60;
private boolean _searchable = false;
private Vector _listData;
private FieldChangeListener _fieldListener;
public CustomListField(Vector data) {
super(FOCUSABLE | VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
setSearchable(true);
setEditable(false);
setListData(data);
}
public void setChangeListener(FieldChangeListener listener) {
// we need to save this listener, because we set it to listen to all new rows
_fieldListener = listener;
int numFields = getFieldCount();
for (int f = 0; f < numFields; f++) {
getField(f).setChangeListener(listener);
}
super.setChangeListener(listener);
}
public int getRowHeight() {
return _MAX_ROW_HEIGHT;
}
public void setSearchable(boolean searchable) {
_searchable = searchable;
}
public int getSelectedIndex() {
return getFieldWithFocusIndex(); // TODO??
}
public Object get(int index) {
return _listData.elementAt(index);
}
public int indexOfList(String prefix, int start) {
if (start >= _listData.size() || !_searchable) {
return -1;
} else {
int result = getSelectedIndex(); // the default result if we find no matches
for (Enumeration e = _listData.elements(); e.hasMoreElements(); ) {
String rowString = (String) e.nextElement();
if (rowString.startsWith(prefix)) {
return _listData.indexOf(rowString);
}
}
return result;
}
}
protected boolean navigationClick(int status, int time) {
CustomListRow focus = (CustomListRow) getFieldWithFocus();
if (focus != null) {
// see if the row wants to process this click
if (!focus.navigationClick(status, time)) {
// let our FieldChangeListener know that this row has been clicked
fieldChangeNotify(getFieldWithFocusIndex());
}
return true;
} else {
return false;
}
}
protected void sublayout(int width, int height) {
int w = Math.min(width, getPreferredWidth());
int h = Math.min(height, getPreferredHeight());
int rowHeight = getRowHeight();
int numRows = getFieldCount();
setExtent(w, h);
setVirtualExtent(w, rowHeight * numRows);
for (int i = 0; i < numRows; i++) {
Field f = getField(i);
setPositionChild(f, 0, rowHeight * i);
layoutChild(f, w, rowHeight);
}
}
public int getPreferredWidth() {
return Display.getWidth();
}
public int getPreferredHeight() {
return Display.getHeight();
}
public void setListData(Vector listData) {
_listData = listData;
if (listData != null) {
int listSize = listData.size();
int numRows = getFieldCount();
for (int s = 0; s < listSize; s++) {
if (s < numRows) {
// we can reuse existing CustomListRows
CustomListRow row = (CustomListRow) getField(s);
row.setData((ListRander) listData.elementAt(s));
} else {
CustomListRow row = new CustomListRow((ListRander) listData.elementAt(s));
row.setChangeListener(_fieldListener);
row.setFocusListener(this);
add(row);
}
}
if (listSize < numRows) {
// delete the excess rows
deleteRange(listSize, numRows - listSize);
}
} else {
deleteAll();
}
invalidate();
}
public void focusChanged(Field field, int eventType) {
// we handle scrolling here, when focus changes between rows
if (eventType == FOCUS_GAINED) {
if (field.getTop() < getVerticalScroll()) {
// field is off the top of the screen, so scroll up
setVerticalScroll(field.getTop());
} else if (field.getTop() >= getVerticalScroll() + getVisibleHeight()) {
// field is off the bottom of the screen, so scroll down
setVerticalScroll(field.getTop() - getVisibleHeight() + getRowHeight());
}
}
}
}
Finally, one row is represented by my CustomListRow class:
public class CustomListRow extends Manager implements FieldChangeListener {
private static final int _MAX_ROW_HEIGHT = 60;
private ListRander _data;
private BitmapField _thumb;
private LabelField _title;
private FocusableBitmapField _star;
private static final Bitmap _starImg = Bitmap.getBitmapResource("star.png");
private static final Bitmap _bgImg = Bitmap.getBitmapResource("listing_bg.png");
private SeparatorField _separator;
private int _fontColor = Color.BLACK;
private boolean _highlighted = false;
private int _width;
// subclass exists to expose focus methods (make public)
private class FocusableBitmapField extends BitmapField {
public FocusableBitmapField() {
super(_starImg, BitmapField.FOCUSABLE | BitmapField.EDITABLE);
}
public void onFocus(int direction) {
super.onFocus(direction);
}
public void onUnfocus() {
super.onUnfocus();
}
}
public CustomListRow(ListRander data) {
super(Field.FOCUSABLE | Manager.NO_VERTICAL_SCROLL | Manager.NO_VERTICAL_SCROLLBAR);
setBackground(BackgroundFactory.createBitmapBackground(_bgImg));
_width = Display.getWidth();
long labelStyle = (DrawStyle.LEFT | DrawStyle.TOP | DrawStyle.ELLIPSIS);
_title = new LabelField("", labelStyle) { // custom anonymous class to change font color
protected void paint(Graphics g) {
int c = g.getColor();
g.setColor(_fontColor);
super.paint(g);
g.setColor(c);
}
};
_title.setFont(Font.getDefault().getFontFamily().getFont(Font.PLAIN, 24));
_thumb = new BitmapField();
_star = new FocusableBitmapField();
_star.setChangeListener(this);
_separator = new SeparatorField() { // custom anonymous class to change separator color
protected void paint(Graphics g) {
int c = g.getColor();
g.setColor(Color.GRAY);
super.paint(g);
g.setColor(c);
}
};
setData(data);
add(_thumb);
add(_title);
add(_star);
add(_separator);
}
public ListRander getData() {
return _data;
}
public void setData(ListRander value) {
if (value != _data) {
_data = value;
_title.setText(value.getTitle());
_thumb.setBitmap(value.getThumb());
}
}
private void onStarClicked() {
Dialog.alert("Star has been clicked or tapped!");
}
private void onRowClicked() {
Dialog.alert("Row has been clicked or tapped!");
}
public void fieldChanged(Field field, int context) {
if (field == _star) {
onStarClicked();
}
}
public boolean navigationClick(int status, int time) {
if (_star.isFocus()) {
onStarClicked();
return true;
} /* else {
onRowClicked();
return true;
} */
return false; // we will not consume this event
}
protected void highlight(boolean onRow) {
_fontColor = onRow ? Color.WHITE : Color.BLACK; // change font color for contrast
_highlighted = onRow;
invalidate();
}
protected void onFocus(int direction) {
// called when focus first transfers to this row, from another Field
if (direction == 1) {
// coming from top to bottom, we highlight the row first, not the star
highlight(true);
} else if (direction == -1) {
// coming from bottom to top, we highlight the star button first, not the row
_star.onFocus(direction);
highlight(false);
}
}
protected void onUnfocus() {
// remove highlighting of the row, if any
highlight(false);
super.onUnfocus();
}
protected int moveFocus(int amount, int status, int time) {
// called when this row already has focus (either on row, or star button)
if (amount > 0) {
// moving top to bottom
if (!_star.isFocus()) {
// we were on the row, now move to the star button
_star.onFocus(1);
highlight(false);
amount--; // consume one unit of movement
}
} else {
// moving from bottom to top
if (_star.isFocus()) {
// we were on the star button, now move back over to the row
_star.onUnfocus();
highlight(true);
amount++; // consume one unit of movement
}
}
return amount;
}
protected boolean touchEvent(net.rim.device.api.ui.TouchEvent event) {
// We take action when the user completes a click (a.k.a. unclick)
int eventCode = event.getEvent();
if ((eventCode == TouchEvent.UNCLICK) || (eventCode == TouchEvent.DOWN)) {
// Get the touch location, within this Manager
int x = event.getX(1);
int y = event.getY(1);
if ((x >= 0) && (y >= 0) && (x < _width) && (y < _MAX_ROW_HEIGHT)) {
int field = getFieldAtLocation(x, y);
if ((field >= 0) && (getField(field) == _star)) {
// Let event propagate to (star) button field
return super.touchEvent(event);
} else {
if (eventCode == TouchEvent.UNCLICK) {
// A completed click anywhere else in this row should popup details for this selection
fieldChangeNotify(1);
onRowClicked();
} else {
// This is just a soft touch (TouchEvent.DOWN), without full click
setFocus();
}
// Consume the event
return true;
}
}
}
// Event wasn't for us, let superclass handle in default manner
return super.touchEvent(event);
}
protected void sublayout(int width, int height) {
height = Math.min(getPreferredHeight(), height);
setExtent(_width, height);
final int margin = 5;
int thumbWidth = _thumb.getPreferredWidth();
layoutChild(_thumb, thumbWidth, _thumb.getPreferredHeight());
setPositionChild(_thumb, margin, margin);
int starWidth = _star.getPreferredWidth();
int starHeight = _star.getPreferredHeight();
layoutChild(_star, starWidth, starHeight);
setPositionChild(_star, width - starWidth - margin, (height - starHeight) / 2);
// this assumes you want margin between all fields, and edges
layoutChild(_title, width - thumbWidth - starWidth - 4 * margin, _title.getPreferredHeight());
setPositionChild(_title, margin + thumbWidth /* + margin */, margin); // TODO?
}
protected void paintBackground(Graphics g) {
super.paintBackground(g);
if (_highlighted) {
// you can't override drawFocus() for a Manager, so we'll handle that here:
int oldColor = g.getColor();
int oldAlpha = g.getGlobalAlpha();
XYRect rect = new XYRect();
g.setGlobalAlpha(150);
g.setColor(Color.BLUE);
getFocusRect(rect);
drawHighlightRegion(g, HIGHLIGHT_FOCUS, true, rect.x, rect.y, rect.width, rect.height);
g.setGlobalAlpha(oldAlpha);
g.setColor(oldColor);
}
}
public int getPreferredWidth() {
return _width;
}
public int getPreferredHeight() {
return _MAX_ROW_HEIGHT;
}
}
Usage
This is how you might use the whole list field (maybe in a Screen class):
public class ListScreen extends MainScreen implements FieldChangeListener {
public ListScreen() {
try {
Vector data = new Vector();
Bitmap icon = Bitmap.getBitmapResource("list_icon.png");
for (int i = 0; i < 15; i++) {
ListRander lr = new ListRander("Product Name " + i, icon);
data.addElement(lr);
}
CustomListField list = new CustomListField(data);
add(list);
list.setChangeListener(this);
} catch (Exception e) {
e.printStackTrace();
}
}
public void fieldChanged(Field field, int context) {
if (field instanceof CustomListRow) {
CustomListRow row = (CustomListRow) field;
Dialog.alert(row.getData().getTitle() + " was selected!");
}
}
}
In my app, it made sense for the CustomListRow itself to handle the equivalent of your star click. However, for me, it did not make sense to have the row click handled that way. So, I let you set a FieldChangeListener on the CustomListField itself, which is called back when any row is selected. See the example above in my screen class. If you want to handle the row click inside the CustomListRow class, too, that's fine. I laid out a onRowClicked() method there. Search in the code for where that's commented out, and you can reactivate, an implement that method (onRowClicked()).
Issues
My app didn't require list searching. I laid out a sample implementation of that, like ListField has. But, I didn't test it. That's your job, if you need it. I just got you started with the CustomListField implementation (see indexOfList()).
I didn't see what your "nav bar" was for. A bar is usually a full-width item, like a status bar, or toolbar. I don't see anything like that in your screenshot. A nav item might be a little arrow at the right side of each row, to bring up details. But, I didn't see that in your screenshot either. So, I ignored that code. If you need a nav bar, you obviously know what it should be, and can add that to my code above.
I couldn't tell whether or not you just added the star as part of the row's background image, or if you had a separate image for that. I added a separate star.png to represent the star. I would assume that clicking the star fills it in, or highlights it, or something. But, you didn't describe that problem, so I assume you can handle that. If you need a custom field to represent the star, that can have selected and unselected images, just post that as a new question.
You had some code that appeared like it was trying to set the row width to 3x the row height, but that didn't match your screen shot. Most lists are full-screen width anyway. So, I remove that code. My CustomListRow class implements getPreferredWidth() and requests the full screen width. Change if you like.
Unlike Android's ListView the BB's ListField is not designed to have a focusable/clickable fields inside of list items. So any attempt to workaround this will have some negative side effects.
A relatively easy/quick workaround would be to switch to VerticalFieldManager (check this other stack overflow question). But if the list is too long (more than several hundreds, I believe) you risk to "eat" too much memory.
If the app is designed for touch screens only, then you can try to stay with ListField + do some manual tracking of touch event coordinates. So when you detect a list field click (in a way you would normally do it) you can check whether the touch coordinates correspond to the star image area (at least on the X axis). I am not going to invent/provide an implementation, but just giving an idea.

Blackberry: How can I make a buttonfield act like toggle button?

I have a single button which I want to use as Start/Stop button. How can I make the buttonfield work as toggle button?
Please help.
Just change button label on fieldChange or navigationClick or touchEvent, don't forget to save toggle state in class member:
class ToggleButtonField extends ButtonField {
int mToggleState = -1;
String[] mLabels = {};
public ToggleButtonField(String[] labels) {
super(CONSUME_CLICK);
if(labels != null && labels.length > 0)
{
mLabels = labels;
mToggleState = 0;
updateLabel();
}
}
private void updateLabel() {
setLabel(mLabels[mToggleState]);
}
protected void fieldChangeNotify(int context) {
mToggleState = getNextToggleState(mToggleState);
updateLabel();
super.fieldChangeNotify(context);
}
private int getNextToggleState(int state) {
int result = mToggleState+1;
if(result >= mLabels.length)
result = 0;
return result;
}
}

Blackberry custom slideshow-style BitmapField manager

Right now, I'm trying to figure out how to implement the following:
Suppose I have a custom Manager that has about 10 or so BitmapFields layed out in a horizontal manner (similar to a slideshow contained in a HFM ) . What I want to achieve is to be able to move the image HFM via touchEvent horizontally, where a BitmapField would take focus on the left-hand side of the custom Manager. In other words, will I have to give a value to setHorizontalScroll and if so, is it a matter of just incrementing that value when the user makes a left or right touch event. Also, how can I get the focus of a Field within a given position on the screen (i.e. the left-most Field on the HFM) when the HFM is scrolling sideways via touchEvent?
1 - yes, setHorizontalScroll should work, don't forget to use HORIZONTAL_SCROLL in manager constructor
2 - try to test each Field getContentRect() for EventTouch getX(int) and getY(int)
UPDATE
To simplify global field position calculation use
public XYPoint getGlobalXY(Field field) {
XYPoint result = new XYPoint(field.getLeft(), field.getTop());
if (field.getManager() != null) {
result.translate(getGlobalXY(field.getManager()));
}
return result;
}
Thread safe message dialog:
public void showMessage(final String message) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.inform(message);
}
});
}
Sample code:
class Scr extends MainScreen {
HorizontalFieldManager hfm;
public Scr() {
add(new LabelField("asdfsad"));
hfm = new HorizontalFieldManager(HORIZONTAL_SCROLL);
for (int i = 0; i < 5; i++) {
Bitmap bmp = new Bitmap(100, 100);
Graphics g = Graphics.create(bmp);
g.setFont(g.getFont().derive(100));
String txt = String.valueOf(i);
int x = g.getFont().getAdvance(txt);
g.drawText(txt, x, 0);
BitmapField bf = new BitmapField(bmp);
hfm.add(bf);
}
add(hfm);
}
protected boolean touchEvent(TouchEvent message) {
if (message.getEvent() == TouchEvent.CLICK) {
int x = message.getX(1);
int y = message.getY(1);
XYRect r = hfm.getExtent();
r.setLocation(getGlobalXY(hfm));
if (r.contains(x, y)) {
XYRect rf = hfm.getField(2).getExtent();
rf.setLocation(getGlobalXY(hfm.getField(2)));
if (x < rf.x) {
showMessage("left side");
} else if (x > rf.X2()) {
showMessage("right side");
} else {
showMessage("field");
}
}
}
return super.touchEvent(message);
}
}

Resources