how can i make the unity gui window dragable - user-interface

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

Related

How to assign OnActivityResult values to the Listview?

I have a Listview and Click Events in the respective listItems and need to get result back from the click events and populate on the List.
My BaseAdapter class is
public class RemnantListAdapter : BaseAdapter<InventorySlabs>
{
private PartialInventory context;
private List<InventorySlabs> RemnantList;
public RemnantListAdapter(PartialInventory partialInventory, List<InventorySlabs> remnantList)
{
this.context = partialInventory;
this.RemnantList = remnantList;
}
public override InventorySlabs this[int position]
{
get
{
return RemnantList[position];
}
}
public override int Count
{
get
{
return RemnantList.Count;
}
}
public override long GetItemId(int position)
{
return position;
}
public override int ViewTypeCount
{
get
{
return Count;
}
}
public override int GetItemViewType(int position)
{
return position;
}
private class remnantHolder : Object
{
public Button EditRemnant1;
public TextView Remnant1 = null;
public TextView Rem_StockNMaterial1 = null;
public TextView Rem_Dimensions1 = null;
public TextView Rem_Status1 = null;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
remnantHolder holder = null;
if (convertView == null)
{
convertView = (convertView ?? context.LayoutInflater.Inflate(Resource.Layout.remnant_list, parent, false));
holder = new remnantHolder();
holder.EditRemnant1 = convertView.FindViewById<Button>(Resource.Id.editRemnant1);
holder.Remnant1 = convertView.FindViewById<TextView>(Resource.Id.remnant1);
holder.Rem_StockNMaterial1 = convertView.FindViewById<TextView>(Resource.Id.remnant_mtrl1);
holder.Rem_Dimensions1 = convertView.FindViewById<TextView>(Resource.Id.remnant_dimens1);
holder.Rem_Status1 = convertView.FindViewById<TextView>(Resource.Id.remnant_status1);
try
{
InventorySlabs remnantModel = this.RemnantList[position];
if (remnantModel != null)
{
holder.Remnant1.Text = "#" + remnantModel.ExtSlabNo;
holder.Rem_StockNMaterial1.Text = remnantModel.SellName + "-" + remnantModel.Depth + "-" + remnantModel.Finish;
double sqft = (remnantModel.Width * remnantModel.Height) / 144;
holder.Rem_Dimensions1.Text = "(" + remnantModel.Width.ToString() + " * " + remnantModel.Height.ToString() + ")" + sqft.ToString("N2");
holder.Rem_Status1.Text = remnantModel.Status;
holder.EditRemnant1.Click += delegate (object sender, System.EventArgs args)
{
if (remnantModel != null)
{
Intent intent = new Intent(context, typeof(EditRemnant));
intent.PutExtra("OpenPopType", 2);
intent.PutExtra("SlabNo", remnantModel.ExtSlabNo);
context.StartActivityForResult(intent, 1);
}
};
}
}
catch (Exception ex)
{
var method = System.Reflection.MethodBase.GetCurrentMethod();
var methodName = method.Name;
var className = method.ReflectedType.Name;
MainActivity.SaveLogReport(className, methodName, ex);
}
convertView.Tag = holder;
}
else
{
holder = (remnantHolder)convertView.Tag;
}
return convertView;
}
public void ActivityResult(int requestCode, Result resultCode, Intent data)
{
switch (requestCode)
{
case 1:
if (data != null)
{
try
{
string remSlab = data.GetStringExtra("extSlabNo");
if (remSlab != null)
{
remnantData.Width = double.Parse(data.GetStringExtra("remWidth"));
remnantData.Height = double.Parse(data.GetStringExtra("remHeight"));
double sqft = (remnantData.Width * remnantData.Height) / 144;
Rem_Dimensions.Text = "(" + remnantData.Width.ToString() + " * " + remnantData.Height.ToString() + ")" + sqft.ToString("N2");
}
}
catch (Exception ex)
{
var method = System.Reflection.MethodBase.GetCurrentMethod();
var methodName = method.Name;
var className = method.ReflectedType.Name;
MainActivity.SaveLogReport(className, methodName, ex);
}
}
break;
}
}
}
In my Main Activity
I am calling the Result as
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
remnantListAdapter.ActivityResult(requestCode, resultCode, data);
}
After editing the details in Edit view of the ListItem and close the Popup, I am not knowing how to Pass the Values to the Holder to Update in Listview.
You could pass the positon to the new activity in the click event and pass it back with the result intent.
For example:
holder.EditRemnant1.Click += delegate (object sender, System.EventArgs args)
{
if (remnantModel != null)
{
Intent intent = new Intent(context, typeof(EditRemnant));
intent.PutExtra("OpenPopType", 2);
intent.PutExtra("SlabNo", remnantModel.ExtSlabNo);
intent.PutExtra("Position", position );
context.StartActivityForResult(intent, 1);
}
};
And in the new activity:
protected override void OnCreate(Bundle savedInstanceState)
{
Intent intent = Intent;
var position =intent.GetIntExtra("Position", -1);
base.OnCreate(savedInstanceState);
Intent data = new Intent();
String text = "extSlabNo";
data.PutExtra("extSlabNo", text);
data.PutExtra("remWidth", 10);
data.PutExtra("remHeight", 20);
data.PutExtra("Position", position);
SetResult(Result.Ok, data);
}
Then you could modify the data in the adapter according to the positon value:
public void ActivityResult(int requestCode, Result resultCode, Intent data)
{
switch (requestCode)
{
case 1:
if (data != null)
{
try
{
string remSlab = data.GetStringExtra("extSlabNo");
int position = data.GetIntExtra("Position", -1);
if (remSlab != null && position >= 0)
{
RemnantList[position].Width = data.GetIntExtra("remWidth", -1);
RemnantList[position].Height = data.GetIntExtra("remHeight", -1);
NotifyDataSetChanged();
}
}
catch (Exception ex)
{
var method = System.Reflection.MethodBase.GetCurrentMethod();
var methodName = method.Name;
var className = method.ReflectedType.Name;
MainActivity.SaveLogReport(className, methodName, ex);
}
}
break;
}
And reset the adapter in MainActivity OnActivityResult() method :
public class MainActivity : AppCompatActivity
{
RemnantListAdapter remnantListAdapter;
ListView listView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
List<InventorySlabs> remnantList = new List<InventorySlabs>();
for(var i = 0; i < 10; i++)
{
InventorySlabs inventorySlabs = new InventorySlabs();
inventorySlabs.Depth = i.ToString();
inventorySlabs.ExtSlabNo = i.ToString();
inventorySlabs.Finish = "Finish" + i.ToString();
inventorySlabs.Height = 200;
inventorySlabs.SellName = "SellName" + i.ToString();
inventorySlabs.Status = "Status" + i.ToString();
inventorySlabs.Width = 400;
remnantList.Add(inventorySlabs);
}
listView = FindViewById<ListView>(Resource.Id.listView1);
remnantListAdapter = new RemnantListAdapter(this, remnantList);
listView.Adapter = remnantListAdapter;
}
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
remnantListAdapter.ActivityResult(requestCode, resultCode, data);
listView.Adapter = remnantListAdapter;
}
}

How to show image on imageview using webservices and json

I am using web service for showing image in imageview. But web service image show in SYSTEM.BYTE[] Format. So how to Convert or display the image in imageview in xamarin android application??
Webservice.asmx:
[WebMethod(MessageName = "BindHospName", Description = "Bind Hospital Name Control")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
[System.Xml.Serialization.XmlInclude(typeof(GetHospName))]
public string BindHosp(decimal SpecID)
{
JavaScriptSerializer objJss = new JavaScriptSerializer();
List<GetHospName> HospName = new List<GetHospName>();
try
{
ConnectionString();
cmd = new SqlCommand("select b.HID,b.HospName,b.Logo from HospitalRegBasic b inner join HospitalRegClinical c on b.HID=c.HID " +
"where b.EmailActivationCode <> '' and b.EmailActivationStatus = 1 and b.Status = 1 and c.SPEC_ID = #SpecID ", conn);
cmd.Parameters.AddWithValue("#SpecID", SpecID);
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
var getHosp = new GetHospName
{
HospID = dr["HID"].ToString(),
HospName = dr["HospName"].ToString(),
HospLogo = dr["Logo"].ToString()
};
HospName.Add(getHosp);
}
}
dr.Close();
cmd.Dispose();
conn.Close();
}
catch (Exception)
{
throw;
}
return objJss.Serialize(HospName);
}
Class.cs:
namespace HSAPP
{
class ContListViewHospNameClass : BaseAdapter<GetHospNames>
{
List<GetHospNames> objList;
Activity objActivity;
public ContListViewHospNameClass (Activity objMyAct, List<GetHospNames> objMyList) : base()
{
this.objActivity = objMyAct;
this.objList = objMyList;
}
public override GetHospNames this[int position]
{
get
{
return objList[position];
}
}
public override int Count
{
get
{
return objList.Count;
}
}
public override long GetItemId(int position)
{
return position;
}
public static Bitmap bytesToBitmap(byte[] imageBytes)
{
Bitmap bitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
return bitmap;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
var item = objList[position];
if (convertView == null)
{
convertView = objActivity.LayoutInflater.Inflate(Resource.Layout.ContListViewHospName, null);
}
convertView.FindViewById<TextView>(Resource.Id.tvHospID).Text = item.HospID;
convertView.FindViewById<TextView>(Resource.Id.tvHospName).Text = item.HospName;
byte[] img =item.HospLogo;
Bitmap bitmap = BitmapFactory.DecodeByteArray(img, 0, img.Length);
convertView.FindViewById<ImageView>(Resource.Id.imgLogo).SetImageBitmap(bitmap);
return convertView;
}
}
}
This is JSON Code:
private void BindControl_BindHospCompleted(object sender, BindControl.BindHospCompletedEventArgs e)
{
jsonValue = e.Result.ToString();
if (jsonValue == null)
{
Toast.MakeText(this, "No Data For Bind", ToastLength.Long).Show();
return;
}
try
{
JArrayValue = JArray.Parse(jsonValue);
list = new List<GetHospNames>();
int count = 0;
while (count < JArrayValue.Count)
{
GetHospNames getHospName = new GetHospNames(JArrayValue[count]["HospID"].ToString(), JArrayValue[count]["HospName"].ToString(),JArrayValue[count]["Logo"]);
list.Add(getHospName);
count++;
}
listView.Adapter = new ContListViewHospNameClass(this, list);
}
catch (Exception ex)
{
Toast.MakeText(this, ex.ToString(), ToastLength.Long).Show();
}
}
public static void SetImageFromByteArray (byte[] iArray, UIImageView imageView)
{
if (iArray != null && iArray.Length > 0) {
Bitmap bitmap = BitmapFactory.DecodeByteArray (iArray, 0, iArray.Length);
imageView.SetImageBitmap (bitmap);
}
}
That's it. If this is not working, your byte array may not be a valid image.
public static bool IsValidImage(byte[] bytes)
{
try {
using(MemoryStream ms = new MemoryStream(bytes))
Image.FromStream(ms);
}
catch (ArgumentException) {
return false;
}
return true;
}

JeroMQ: connection does not recover reliably

I have two applications, sending messages asynchronously in both directions. I am using sockets of type ZMQ.DEALER on both sides. The connection status is additionally controlled by heartbeating.
I have now problems to get the connection reliably recovering after connection problems (line failure or application restart on one side). When I restart the applicaton on the server side (the side doing the bind()), the client side will not always reconnect successfully and then needs to be restarted, especially when the local buffer has reached the HWM limit.
I did not find any other way to make the connection recovery reliable, other than resetting the complete ZMQ.Context in case of heartbeat failures or if send() returned false. I will then call Context.term() and will create Context and Socket again. This seemed to work fine in my tests. But now I observed occasional and hangups inside Context.term(), which are rare and hard to reproduce. I know, that creating the Context should be done just once at application startup, but as said I found no other way to re-establish a broken connection.
I am using JeroMQ 0.3.4. The source of a test application is below, ~200 lines of code.
Any hints to solve this are very much appreciated.
import java.util.Calendar;
import org.zeromq.ZMQ;
public class JeroMQTest {
public interface IMsgListener {
public void newMsg(byte[] message);
}
final static int delay = 100;
final static boolean doResetContext = true;
static JeroMQTest jeroMQTest;
static boolean isServer;
private ZMQ.Context zContext;
private ZMQ.Socket zSocket;
private String address = "tcp://localhost:9889";
private long lastHeartbeatReceived = 0;
private long lastHeartbeatReplyReceived;
private boolean sendStat = true, serverIsActive = false, receiverInterrupted = false;
private Thread receiverThread;
private IMsgListener msgListener;
public static void main(String[] args) {
isServer = args.length > 0 && args[0].equals("true");
if (isServer) {
new JeroMQTest().runServer();
}
else {
new JeroMQTest().runClient();
}
}
public void runServer() {
msgListener = new IMsgListener() {
public void newMsg(byte[] message) {
String msgReceived = new String(message);
if (msgReceived.startsWith("HEARTBEAT")) {
String msgSent = "HEARTBEAT_REP " + msgReceived.substring(10);
sendStat = zSocket.send(msgSent.getBytes());
System.out.println("heartbeat rcvd, reply sent, status:" + sendStat);
lastHeartbeatReceived = getNow();
} else {
System.out.println("msg received:" + msgReceived);
}
}
};
createJmq();
sleep(1000);
int ct = 1;
while (true) {
boolean heartbeatsOk = lastHeartbeatReceived > getNow() - delay * 4;
if (heartbeatsOk) {
serverIsActive = true;
String msg = "SERVER " + ct;
sendStat = zSocket.send(msg.getBytes());
System.out.println("msg sent:" + msg + ", status:" + sendStat);
ct++;
}
if (serverIsActive && (!heartbeatsOk || !sendStat)) {
serverIsActive = false;
if (doResetContext) {
resetContext();
}
}
sleep(delay);
}
}
public void runClient() {
msgListener = new IMsgListener() {
public void newMsg(byte[] message) {
String msgReceived = new String(message);
if (msgReceived.startsWith("HEARTBEAT_REP")) {
System.out.println("HEARTBEAT_REP received:" + msgReceived);
lastHeartbeatReplyReceived = getNow();
}
else {
System.out.println("msg received:" + msgReceived);
}
}
};
createJmq();
sleep(1000);
int ct = 1;
boolean reconnectDone = false;
while (true) {
boolean heartbeatsOK = lastHeartbeatReplyReceived > getNow() - delay * 4;
String msg = "HEARTBEAT " + (ct++);
sendStat = zSocket.send(msg.getBytes());
System.out.println("heartbeat sent:" + msg + ", status:" + sendStat);
sleep(delay / 2);
if (sendStat) {
msg = "MSG " + ct;
sendStat = zSocket.send(msg.getBytes());
System.out.println("msg sent:" + msg + ", status:" + sendStat);
reconnectDone = false;
}
if ((!heartbeatsOK && lastHeartbeatReplyReceived > 0) || (!sendStat && !reconnectDone)) {
if (doResetContext) {
resetContext();
}
lastHeartbeatReplyReceived = 0;
reconnectDone = true;
}
sleep(delay / 2);
}
}
public void resetContext() {
closeJmq();
sleep(1000);
createJmq();
System.out.println("resetContext done");
}
private void createJmq() {
zContext = ZMQ.context(1);
zSocket = zContext.socket(ZMQ.DEALER);
zSocket.setSendTimeOut(100);
zSocket.setReceiveTimeOut(100);
zSocket.setSndHWM(10);
zSocket.setRcvHWM(10);
zSocket.setLinger(100);
if (isServer) {
zSocket.bind(address);
} else {
zSocket.connect(address);
}
receiverThread = new Thread() {
public void run() {
receiverInterrupted = false;
try {
ZMQ.Poller poller = new ZMQ.Poller(1);
poller.register(zSocket, ZMQ.Poller.POLLIN);
while (!receiverInterrupted) {
if (poller.poll(100) > 0) {
byte byteArr[] = zSocket.recv(0);
msgListener.newMsg(byteArr);
}
}
poller.unregister(zSocket);
} catch (Throwable e) {
System.out.println("Exception in ReceiverThread.run:" + e.getMessage());
}
}
};
receiverThread.start();
}
public void closeJmq() {
receiverInterrupted = true;
sleep(100);
zSocket.close();
zContext.term();
}
long getNow() {
Calendar now = Calendar.getInstance();
return (long) (now.getTime().getTime());
}
private static void sleep(int mSleep) {
try {
Thread.sleep(mSleep);
} catch (InterruptedException e) {
}
}
}

GWT - Fading in/out a background image

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

BlackBerry - Custom menu toolbar

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

Resources