Blackberry - Custom size EditField - user-interface

I am trying to put together a dialog that should look like this:
Fill in the below fields
_______________ likes ____________________
where the "_" lines are the EditFields.
I am sticking all the fields in a HorizontalFieldManager, which I add to the dialog. Unfortunately, the first EditField consumes all the space on the first line. I have tried to override the getPreferredWidth() method of the EditField by creating my own class extending BasicEditField, but have had no success.
Surely there must be a simple way to force a certain size for an edit field. What am I missing?

Just like DaveJohnston said:
class LikesHFManager extends HorizontalFieldManager {
EditField mEditFieldLeft;
LabelField mLabelField;
EditField mEditFieldRight;
String STR_LIKES = "likes";
int mLabelWidth = 0;
int mEditWidth = 0;
int mOffset = 4;
public LikesHFManager() {
mEditFieldLeft = new EditField();
mLabelField = new LabelField(STR_LIKES);
mEditFieldRight = new EditField();
mLabelWidth = mLabelField.getFont().getAdvance(STR_LIKES);
int screenWidth = Display.getWidth();
mEditWidth = (screenWidth - mLabelWidth) >> 1;
mEditWidth -= 2 * mOffset;
// calculate max with of one character
int chMaxWith = mEditFieldLeft.getFont().getAdvance("W");
// calculate max count of characters in edit field
int chMaxCnt = mEditWidth / chMaxWith;
mEditFieldLeft.setMaxSize(chMaxCnt);
mEditFieldRight.setMaxSize(chMaxCnt);
add(mEditFieldLeft);
add(mLabelField);
add(mEditFieldRight);
}
protected void sublayout(int maxWidth, int maxHeight) {
int x = 0;
int y = 0;
int editHeight = mEditFieldLeft.getPreferredHeight();
int labelHeight = mLabelField.getPreferredHeight();
setPositionChild(mEditFieldLeft, x, y);
layoutChild(mEditFieldLeft, mEditWidth, editHeight);
x += mEditWidth;
x += mOffset;
setPositionChild(mLabelField, x, y);
layoutChild(mLabelField, mLabelWidth, labelHeight);
x += mLabelWidth;
x += mOffset;
setPositionChild(mEditFieldRight, x, y);
layoutChild(mEditFieldRight, mEditWidth, editHeight);
x += mEditWidth;
setExtent(x, Math.max(labelHeight, editHeight));
}
}

Try subclassing HorizontalFieldManager and override the sublayout method:
protected void sublayout(int maxWidth, int maxHeight) { }
In this method you should call setPositionChild() and layoutChild() for each component you are adding so you can control the positioning and size of each.
You should also override the layout method of each component and call
setExtent(getPreferredWidth(), getPreferredHeight());
this will make use of your implementation of the getPreferred... methods you have already written.
Hope this helps.

Building on Max Gontar's solution, this should solve the general problem of assigning width to sub Fields of HorizontalFieldManagers:
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.*;
public class FieldRowManager extends HorizontalFieldManager {
public FieldRowManager(final long style)
{
super(style);
}
public FieldRowManager()
{
this(0);
}
private SubField FirstSubField = null;
private SubField LastSubField = null;
private static class SubField
{
public final Field Field;
public final int Width;
public final int Offset;
private SubField Next;
public SubField(final FieldRowManager container, final Field field, final int width, final int offset)
{
Field = field;
Width = width;
Offset = offset;
if (container.LastSubField == null)
{
container.FirstSubField = this;
}
else
{
container.LastSubField.Next = this;
}
container.LastSubField = this;
}
public SubField getNext()
{
return Next;
}
}
public void add(final Field field)
{
add(field, field.getPreferredWidth());
}
public void add(final Field field, final int width)
{
add(field, width, 0);
}
public void add(final Field field, final int width, final int offset)
{
new SubField(this, field, width, offset);
super.add(field);
}
protected void sublayout(final int maxWidth, final int maxHeight)
{
int x = 0;
int height = 0;
SubField subField = FirstSubField;
while (subField != null)
{
final Field field = subField.Field;
final int fieldHeight = field.getPreferredHeight();
this.setPositionChild(field, x, 0);
this.layoutChild(field, subField.Width, fieldHeight);
x += subField.Width+subField.Offset;
if (fieldHeight > height)
{
height = fieldHeight;
}
subField = subField.getNext();
}
this.setExtent(x, height);
}
}
Just call the overloads of the add method to specify the width, and the offset space before the next Field. Though this does not allow for deleting/replacing Fields.
It is irksome that RIM does not provide this functionality in the standard library. HorizontalFieldManager should just work this way.

Related

GUITexture disapears when I add a transform position & quaternion.identity

I'm trying to create a health system for my 2d asteroid shoooter. I have the health icons instantiating now using:
Transform newHealthIcon = ((GameObject)Instantiate(healthIconGUI.gameObject)).transform;
However, when I try and set it's transform position and rotation the texture becomes invisible and no longer shows.
Transform newHealthIcon = ((GameObject)Instantiate(healthIconGUI.gameObject, transform.position, Quaternion.identity)).transform;
Here's the full code:
using UnityEngine;
using System.Collections;
public class Health : MonoBehaviour {
public int startingHealth;
public int healthPerIcon;
public GUITexture healthIconGUI;
private ArrayList healthIcons = new ArrayList();
public int maxIconsPerRow;
private float spacingX;
private float spacingY;
void Start () {
spacingX = healthIconGUI.pixelInset.width;
spacingY = healthIconGUI.pixelInset.height;
AddHealth (startingHealth / healthPerIcon);
}
public void AddHealth(int n) {
for (int i = 0; i < n; i++) {
Transform newHealthIcon = ((GameObject)Instantiate(healthIconGUI.gameObject, transform.position, Quaternion.identity)).transform;
newHealthIcon.parent = transform;
int y = Mathf.FloorToInt(healthIcons.Count / maxIconsPerRow);
int x = healthIcons.Count - y * maxIconsPerRow;
newHealthIcon.GetComponent<GUITexture> ().pixelInset = new Rect(x * spacingX, y * spacingY, 1, 1);
healthIcons.Add (newHealthIcon);
}
}
public void ModifyHealth (int amount) {
}
}

No suitable method found in my overriden methods mono for android

I'm trying to draw a line based on touch event. Basically it draws line as the finger moves. I'm getting an error when overriding ontouchevent and onsizechanged. It was originally written in JAVA. I just translated it to C#. Here's the code:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
currentLevel = Intent.GetIntExtra("gameLevel", 0);
playerScore = Intent.GetIntExtra("score", 0);
SetContentView(new SampleView(this));
// Create your application here
}
private class SampleView : View
{
private Paint mPaint;
private static Bitmap m_bitmap;
private DisplayMetrics m_metrics;
private Canvas m_canvas;
private Path m_path;
private Paint m_bitmapPaint;
private float m_X, m_Y;
static bool m_pathDrawn = false;
private static float TOUCH_TOLERANCE = 4;
public SampleView(Context context)
: base(context)
{
Focusable = true;
mPaint = new Paint();
mPaint.AntiAlias = true;
mPaint.Dither = true;
mPaint.SetStyle(Paint.Style.Stroke);
mPaint.StrokeWidth = 12;
mPaint.StrokeJoin = Paint.Join.Round;
mPaint.StrokeCap = Paint.Cap.Round;
m_metrics = context.Resources.DisplayMetrics;
m_bitmap = Bitmap.CreateBitmap(m_metrics.WidthPixels, m_metrics.HeightPixels, Bitmap.Config.Argb8888);
m_canvas = new Canvas(m_bitmap);
m_bitmapPaint = new Paint();
}
public void onerase()
{
m_canvas = null;
}
protected override void onSizeChanged(int p_w, int p_h, int p_oldw, int p_oldh)
{
this.onSizeChanged(p_w, p_h, p_oldw, p_oldh);
}
protected override void OnDraw(Canvas canvas)
{
canvas.DrawColor(Color.Black);
canvas.DrawBitmap(m_bitmap, 0, 0, m_bitmapPaint);
canvas.DrawPath(m_path, mPaint);
}
private void touch_start(float p_x, float p_y)
{
m_path.Reset();
m_path.MoveTo(p_x, p_y);
m_X = p_x;
m_Y = p_y;
}
private void touch_move(float p_x, float p_y)
{
float m_dx = Math.Abs(p_x - m_X);
float m_dy = Math.Abs(p_y - m_Y);
if (m_dx >= TOUCH_TOLERANCE || m_dy >= TOUCH_TOLERANCE)
{
m_path.QuadTo(m_X, m_Y, (p_x + m_X) / 2, (p_y + m_Y) / 2);
m_X = p_x;
m_Y = p_y;
m_pathDrawn = true;
}
}
private void touch_up()
{
m_path.LineTo(m_X, m_Y);
// commit the path to our offscreen
m_canvas.DrawPath(m_path, mPaint);
// kill this so we don't double draw
m_path.Reset();
}
public override bool onTouchEvent(MotionEvent p_event)
{
float m_x = p_event.GetX();
float m_y = p_event.GetY();
switch (p_event.Action)
{
case MotionEventActions.Down:
touch_start(m_x, m_y);
Invalidate();
break;
case MotionEventActions.Move:
touch_move(m_x, m_y);
Invalidate();
break;
case MotionEventActions.Up:
touch_up();
Invalidate();
break;
}
return true;
}
}
Another thing. I want to make my image view from a layout as my canvas and draw the line there ontouchevent. How should I do this? Thanks!
Method name should use pascal casing.
Android.Views.View.OnTouchEvent Method
Android.Views.View.OnSizeChanged Method
public override bool OnTouchEvent(MotionEvent e)
{
}
protected override void OnSizeChanged(int w, int h, int oldw, int oldh)
{
}
Mono coding guidelines.

Custom buttons aren't displaying on my UI

I'm creating a simple blackberry application for testing purposes and my custom buttons do not show on the UI of the simulator.
I've created a custom button called CustomButtonField and here is the code:
package test.expense;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
public class CustomButtonField extends Field {
String label;
int backgroundColor;
int foregroundColor;
public CustomButtonField(String label, int backgroundColor, int foregroundColor, long style){
super(style);
this.label = label;
this.backgroundColor = backgroundColor;
this.foregroundColor = foregroundColor;
}
public int getPreferedHeight(){
return getFont().getHeight() + 8;
}
public int getPreferedWidth(){
return getFont().getAdvance(label) + 8;
}
protected void layout(int width, int height) {
setExtent(Math.min(width, getPreferredWidth()), Math.min(height, getPreferredHeight()));
}
protected void paint(Graphics graphics) {
graphics.setColor(backgroundColor);
graphics.fillRoundRect(1, 1, getWidth()-2, getHeight()-2, 12, 12);
graphics.setColor(foregroundColor);
graphics.drawText(label, 4, 4);
}
}
And here is where I invoke it and display it:
HorizontalFieldManager buttonManager = new HorizontalFieldManager(FIELD_RIGHT);
CustomButtonField btnCancel;
CustomButtonField btnSubmit;
public ExpenseSheetScreen() {
super();
btnCancel = new CustomButtonField("Cancel", Color.WHITE, 0x716eb3, 0);
btnCancel.setChangeListener(this);
btnSubmit = new CustomButtonField("Submit", Color.WHITE, 0x716eb3, 0);
btnSubmit.setChangeListener(this);
buttonManager.add(btnCancel);
buttonManager.add(btnSubmit);
add(buttonManager);
}// End Expense Sheet Screen.
What am I doing wrong?
protected void layout(int width, int height) {
setExtent(Math.min(width, getPreferredWidth()),
Math.min(height, getPreferredHeight()));
}
setExtend is set to 0, 0 all the time.

Blackberry - Listfield layout question

I'm having an interesting anomaly when displaying a listfield on the blackberry simulator:
The top item is the height of a single line of text (about 12 pixels) while the rest are fine.
Does anyone know why only the top item is being drawn this way? Also, when I add an empty venue in position 0, it still displays the first actual venue this way (item in position 1).
Not sure what to do.
Thanks for any help.
The layout looks like this:
-----------------------------------
| *part of image* | title |
-----------------------------------
| | title |
| * full image * | address |
| | city, zip |
-----------------------------------
The object is called like so:
listField = new ListField( venueList.size() );
listField.setCallback( this );
listField.setSelectedIndex(-1);
_middle.add( listField );
Here is the drawListRow code:
public void drawListRow( ListField listField, Graphics graphics,
int index, int y, int width )
{
listField.setRowHeight(90);
Hashtable item = (Hashtable) venueList.elementAt( index );
String venue_name = (String) item.get("name");
String image_url = (String) item.get("image_url");
String address = (String) item.get("address");
String city = (String) item.get("city");
String zip = (String) item.get("zip");
EncodedImage img = null;
try
{
String filename = image_url.substring(image_url.indexOf("crop/")
+ 5, image_url.length() );
FileConnection fconn = (FileConnection)Connector.open(
"file:///SDCard/Blackberry/project1/" + filename,
Connector.READ);
if ( !fconn.exists() )
{
}
else
{
InputStream input = fconn.openInputStream();
byte[] data = new byte[(int)fconn.fileSize()];
input.read(data);
input.close();
if(data.length > 0)
{
EncodedImage rawimg = EncodedImage.createEncodedImage(
data, 0, data.length);
int dw = Fixed32.toFP(Display.getWidth());
int iw = Fixed32.toFP(rawimg.getWidth());
int sf = Fixed32.div(iw, dw);
img = rawimg.scaleImage32(sf * 4, sf * 4);
}
else
{
}
}
}
catch(IOException ef)
{
}
graphics.drawText( venue_name, 140, y, 0, width );
graphics.drawText( address, 140, y + 15, 0, width );
graphics.drawText( city + ", " + zip, 140, y + 30, 0, width );
if(img != null)
{
graphics.drawImage(0, y, img.getWidth(), img.getHeight(),
img, 0, 0, 0);
}
}
setRowHeight should be called once after construction of ListField, not inside of drawListRow on each time row is repainted:
listField = new ListField( venueList.size() );
listField.setRowHeight(90);
listField.setCallback( this );
listField.setSelectedIndex(-1);
_middle.add( listField );
Aman,
Hopefully you can use this for something. You should be able to extract the list field data from this wildly out of control class. Remember, this is a work in progress, so you will have to strip out the things that are quite clearly custom to my app. Like the image handling that relies on a substring for a file name.
It works fine for me, but it will totally not work for anyone htat just copies and pastes, so good luck...
package venue;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import net.rim.device.api.math.Fixed32;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.FocusChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
public class categoryView extends MainScreen implements FieldChangeListener, ListFieldCallback, FocusChangeListener {
private HorizontalFieldManager _top;
private HorizontalFieldManager _nav;
private VerticalFieldManager _middle;
private int horizontalOffset;
private final static long animationTime = 300;
private long animationStart = 0;
private int venue_id;
private int category_id;
private CustomButtonField rectangle;
private Vector venueList = new Vector();
private Hashtable venue_index = new Hashtable();
private Vector image_index = new Vector();
private ListField listField;
private int last_menu_item = 2;
private int last_nav = 2;
private int before_last = 1;
private int location_count = 0;
private int img_width = 120;
private int img_height = 80;
private Field f;
public categoryView(int id) {
super();
category_id = id;
horizontalOffset = Display.getWidth();
_top = new HorizontalFieldManager(Manager.USE_ALL_WIDTH | Field.FIELD_HCENTER)
{
public void paint(Graphics gr)
{
Bitmap bg = Bitmap.getBitmapResource("bg.png");
gr.drawBitmap(0, 0, Display.getWidth(), Display.getHeight(), bg, 0, 0);
subpaint(gr);
}
};
_nav = new HorizontalFieldManager(Field.USE_ALL_WIDTH);
_middle = new VerticalFieldManager();
add(_top);
add(_nav);
add(_middle);
Bitmap lol = Bitmap.getBitmapResource("logo.png");
BitmapField lolfield = new BitmapField(lol);
_top.add(lolfield);
HorizontalFieldManager nav = new HorizontalFieldManager(Field.USE_ALL_WIDTH | Manager.HORIZONTAL_SCROLL);
Vector locs = getLocations();
Hashtable locations = (Hashtable) locs.elementAt(0);
Enumeration ne = locations.keys();
Enumeration nv = locations.elements();
int counter = 1;
if(locations.size() > 1)
{
counter = locations.size() - 1;
}
int count = 1;
while(ne.hasMoreElements())
{
final String location_id = ne.nextElement().toString();
String location = nv.nextElement().toString();
last_nav = Integer.parseInt(location_id);
rectangle = new CustomButtonField(location_id, location, 25, Field.FOCUSABLE);
rectangle.setFocusListener(this);
nav.add(rectangle);
if(count == counter)
{
before_last = Integer.parseInt(location_id);
}
count ++;
}
_nav.add(nav);
}
public void setDefaultLocation()
{
Vector locs = getLocations();
Hashtable loc1 = (Hashtable) locs.elementAt(0);
Enumeration er = loc1.keys();
Enumeration vr = loc1.elements();
int i = 0;
while(er.hasMoreElements())
{
final String location_id = er.nextElement().toString();
if(i == 0)
{
last_menu_item = Integer.parseInt(location_id);
}
i ++;
}
}
public void drawMiddle()
{
Vector venues = getVenues(category_id);
Hashtable venue_list = (Hashtable) venues.elementAt(0);
Enumeration e = venue_list.keys();
Enumeration v = venue_list.elements();
int count = 0;
while(e.hasMoreElements())
{
String vid = e.nextElement().toString();
Hashtable elm = (Hashtable)v.nextElement();
venueList.addElement(elm);
venue_index.put(Integer.toString(count), (String) elm.get("venue_id"));
EncodedImage img = null;
String image_url = (String) elm.get("image_url");
try
{
String filename;
if(image_url.length() > 5)
{
filename = image_url.substring( image_url.indexOf("crop/") + 5, image_url.length() );
}
else
{
filename = "1.png";
}
FileConnection fconn = (FileConnection) Connector.open( "file:///SDCard/Blackberry/venue/" + filename, Connector.READ);
if ( !fconn.exists() )
{
}
else
{
InputStream input = fconn.openInputStream();
byte[] data = new byte[(int)fconn.fileSize()];
input.read(data);
input.close();
if(data.length > 0)
{
EncodedImage rawimg = EncodedImage.createEncodedImage(data, 0, data.length);
int dw = Fixed32.toFP(Display.getWidth());
int iw = Fixed32.toFP(rawimg.getWidth());
int sf = Fixed32.div(iw, dw);
img = rawimg.scaleImage32(sf * 4, sf * 4);
img_width = (int) Math.ceil(Display.getWidth() / 4);
img_height = (int) Math.ceil(Display.getWidth() / 6);
}
else
{
}
}
}
catch(IOException ef)
{
}
image_index.addElement(img);
count ++;
}
final int count_results = count;
_middle = new VerticalFieldManager( Manager.VERTICAL_SCROLLBAR )
{
public void paint(Graphics graphics)
{
graphics.setBackgroundColor(0xFFFFFF);
graphics.setColor(Color.BLACK);
graphics.clear();
super.paint(graphics);
}
protected void sublayout(int maxWidth, int maxHeight)
{
int displayWidth = Display.getWidth();
//int displayHeight = Display.getHeight();
int displayHeight = count_results * img_height;
super.sublayout( displayWidth, displayHeight);
setExtent( displayWidth, displayHeight);
}
};
add(_middle);
listField = new ListField( venueList.size() );
listField.setCallback( this );
listField.setSelectedIndex(-1);
listField.setRowHeight(img_height);
_middle.add( listField );
_middle.add(new RichTextField(Field.NON_FOCUSABLE));
}
public boolean navigationClick(int status, int time) {
Field focus = UiApplication.getUiApplication().getActiveScreen() .getLeafFieldWithFocus();
if (focus instanceof ListField) {
int selected = listField.getSelectedIndex();
String venue_id = (String) venue_index.get(Integer.toString(selected));
moveScreens(venue_id);
}
return true;
}
void setListSize()
{
listField.setSize( venueList.size() );
}
public void drawListRow( ListField listField, Graphics graphics, int index, int y, int width )
{
Hashtable item = (Hashtable) venueList.elementAt( index );
String venue_name = (String) item.get("name");
String address = (String) item.get("address");
String city = (String) item.get("city");
String zip = (String) item.get("zip");
EncodedImage img = (EncodedImage) image_index.elementAt(index);
graphics.drawText( venue_name, img_width + 10, y, 0, width );
graphics.drawText( address, img_width + 10, y + 15, 0, width );
graphics.drawText( city + ", " + zip, img_width + 10, y + 30, 0, width );
if(img != null)
{
graphics.drawImage(0, y + 3, img.getWidth(), img.getHeight(), img, 0, 0, 0);
}
}
public Object get( ListField listField, int index )
{
return venueList.elementAt( index );
}
public Vector getCategories()
{
Vector results = new Vector();
database db = new database();
Vector categories = db.getCategories();
if(categories.size() > 0)
results = categories;
return results;
}
public Vector getLocations()
{
Vector results = new Vector();
database db = new database();
Vector subcats = db.getCategoryLocations(category_id);
Hashtable subs = (Hashtable) subcats.elementAt(0);
if(subs.size() > 0)
{
location_count = subs.size();
results = subcats;
}
return results;
}
public Vector getVenues(int category_id)
{
Vector results = new Vector();
database db = new database();
Vector venues = db.getLocationVenues(category_id, last_menu_item);
if(venues.size() > 0)
results = venues;
return results;
}
protected void makeMenu(Menu menu, int instance)
{
super.makeMenu(menu, instance);
menu.add(new MenuItem("Home", 10, 20){
public void run()
{
moveScreens("main");
}
});
menu.add(new MenuItem("Search", 10, 20){
public void run()
{
Dialog.inform("Search was clicked.");
}
});
Vector locs = getLocations();
Hashtable locations = (Hashtable) locs.elementAt(0);
Enumeration e = locations.keys();
Enumeration v = locations.elements();
while(e.hasMoreElements())
{
final String location_id = e.nextElement().toString();
String location = v.nextElement().toString();
menu.add(new MenuItem(location, 10, 20){
public void run()
{
Dialog.inform("Location " + location_id + " was clicked");
}
});
}
}
public void moveScreens(String type)
{
if(type == "main")
{
UiApplication.getUiApplication().popScreen(this);
}
else
{
int venue_id = Integer.parseInt(type);
Screen newScreen = new ViewVenue(venue_id);
UiApplication.getUiApplication().pushScreen(newScreen);
}
}
protected void sublayout(int width, int height)
{
super.sublayout(width, height);
if(horizontalOffset > 0)
{
if(animationStart == 0)
{
animationStart = System.currentTimeMillis();
}
else
{
long timeElapsed = System.currentTimeMillis() - animationStart;
if(timeElapsed >= animationTime)
{
horizontalOffset = 0;
}
else
{
float percentDone = (float)timeElapsed / (float)animationTime;
horizontalOffset = Display.getWidth() - (int)(percentDone * Display.getWidth());
}
}
}
setPosition(horizontalOffset, 0);
if(horizontalOffset > 0)
{
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run()
{
updateLayout();
}
});
}
}
public void fieldChanged(Field field, int context)
{
int id = 0;
if (field instanceof CustomButtonField) {
id = ((CustomButtonField)field).getId();
}
venue_id = id;
Dialog.inform(Integer.toString(venue_id));
//moveScreens("venue");
}
public void focusChanged(Field field, int eventType) {
if((eventType == FocusChangeListener.FOCUS_GAINED)) {
if (field instanceof CustomButtonField) {
final int id = ((CustomButtonField)field).getId();
if(id == last_nav && before_last != last_menu_item && last_nav != before_last)
{
//updateContent(id);
f.setFocus();
}
else
{
updateContent(id);
f = field;
}
}
}
}
public void updateContent(final int id)
{
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run()
{
delete(_middle);
venueList.removeAllElements();
image_index.removeAllElements();
last_menu_item = id;
drawMiddle();
}
});
}
public boolean onSavePrompt()
{
// do nothing
return true;
}
public int getPreferredWidth(ListField listField) {
// TODO Auto-generated method stub
return 0;
}
public int indexOfList(ListField listField, String prefix, int start) {
// TODO Auto-generated method stub
return 0;
}
}

How do I color LabelField text within a ListField when the parent manager has the focus?

I have an overridden LabelField that allows me to change the font color based on whether an item in my ListField should be subdued or now. Making the LabelField color subdued works great. But, when the row (that contains my LabelField) is highlighted in the ListField, I would like the label field color to be different or inverted.
Here is my code:
public class MyLabelField extends LabelField{
public MyLabelField (String s, long l){
super(s, l);
m_bSubdue = true; // this value does change in implementation but not in this sample
}
protected void paint(Graphics g)
{
if(m_bSubdue && !this.isFocus()){ // this isFocus() trick is not working
int color = 0x00696969; // RGB val
g.setColor(color);
}
super.paint(g);
}
boolean m_bSubdue;
}
In this sample, I would like MyLabelField to be drawn with a gray color but when the ListField row its contained in has the focus, I would like the color to default to LabelField paint which should make it white.
Based on testing my code, it seems the LabelField does not get the focus when its parent row has the focus. Maybe a change is needed somewhere else in my code...
To switch color of LabelField we can check if it's selected in it's paint() method. But even then we'll have to repaint every row in ListField. And that's the problem: every time row selection of ListField is changed, there are only two calls of ListFieldCallback.drawRow() method - first for previous selected row (still in selected state) and second for new selected row (already in selected state)...
I've tried to save previous selected row index and redraw it on each call of drawRow(), but by some reason LabelField.paint() method was not triggered then.
So I come with simple, somehow ugly solution: schedule ListField.invalidate() TimerTask. Period in 100 ms is enough and doesn't hit performance as well.
Jason Emerick's code I've been used as a guide to extended ListField.
class LabelListField extends ListField implements ListFieldCallback {
private Vector mValues;
private Vector mRows;
public LabelListField(Vector values) {
super(0);
setRowHeight(70);
setCallback(this);
mValues = values;
fillListWithValues(values);
scheduleInvalidate();
}
private void scheduleInvalidate() {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
invalidate();
}
}, 0, 100);
}
private void fillListWithValues(Vector values) {
mRows = new Vector();
for (int i = 0; i < values.size(); i++) {
TableRowManager row = new TableRowManager();
String title = "Item# " + String.valueOf(i + 1);
LabelField titleLabel = new LabelField(title);
titleLabel.setFont(Font.getDefault().derive(Font.BOLD));
row.add(titleLabel);
String value = (String) values.elementAt(i);
ListLabel valueLabel = new ListLabel(this, i, value);
valueLabel.setFont(Font.getDefault().derive(Font.ITALIC));
row.add(valueLabel);
mRows.addElement(row);
}
setSize(mRows.size());
}
private class TableRowManager extends Manager {
public TableRowManager() {
super(0);
}
public void drawRow(Graphics g, int x, int y,
int width, int height) {
layout(width, height);
setPosition(x, y);
g.pushRegion(getExtent());
paintChild(g, getField(0));
paintChild(g, getField(1));
g.popContext();
}
protected void sublayout(int width, int height) {
int fontHeight = Font.getDefault().getHeight();
int preferredWidth = getPreferredWidth();
Field field = getField(0);
layoutChild(field, preferredWidth - 5, fontHeight + 1);
setPositionChild(field, 5, 3);
field = getField(1);
layoutChild(field, preferredWidth - 5, fontHeight + 1);
setPositionChild(field, 5, fontHeight + 6);
setExtent(preferredWidth, getPreferredHeight());
}
public int getPreferredWidth() {
return Display.getWidth();
}
public int getPreferredHeight() {
return getRowHeight();
}
}
public void drawListRow(ListField listField, Graphics g,
int index, int y, int width) {
LabelListField list = (LabelListField) listField;
TableRowManager rowManager = (TableRowManager) list.mRows
.elementAt(index);
rowManager.drawRow(g, 0, y, width, list.getRowHeight());
}
public Object get(ListField list, int index) {
return mValues.elementAt(index);
}
public int indexOfList(ListField list, String prefix, int start) {
for (int x = start; x < mValues.size(); ++x) {
String value = (String) mValues.elementAt(x);
if (value.startsWith(prefix)) {
return x;
}
}
return -1;
}
public int getPreferredWidth(ListField list) {
return Display.getWidth();
}
class ListLabel extends LabelField {
int mIndex = -1;
public ListLabel(LabelListField list, int index, String text) {
super(text);
mIndex = index;
}
protected void paint(Graphics graphics) {
if (getSelectedIndex() == mIndex)
graphics.setColor(Color.RED);
else
graphics.setColor(Color.BLUE);
super.paint(graphics);
}
}
}

Resources