Thursday, December 20, 2012

BlackBerry Custom ImageButton

To achieve this we just need to write a program as follows. make a java class with name ImageButton and copy the below code to this file:


import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;

public class ImageButton extends Field {

private Bitmap _currentPicture;
private Bitmap _onPicture;
private Bitmap _offPicture;
private int id;

public ImageButton(Bitmap onImage, Bitmap offImage) {
super(Field.FIELD_HCENTER | Field.FIELD_VCENTER
| Field.HIGHLIGHT_SELECT | Field.FOCUSABLE);
_offPicture = offImage;
_onPicture = onImage;
_currentPicture = _onPicture;
}

public void setButtonId(int id) {
this.id = id;
}

public int getButtonId() {
return this.id;
}

public int getPreferredHeight() {
return _onPicture.getHeight();
}

public int getPreferredWidth() {
return _onPicture.getWidth();
}

protected void onFocus(int direction) {
_currentPicture = _offPicture;
invalidate();
}

protected void onUnfocus() {
_currentPicture = _onPicture;
invalidate();
}

protected void drawFocus(Graphics g, boolean on) {
g.setBackgroundColor(Color.WHITE);
}

protected void layout(int width, int height) {
setExtent(Math.min(width, getPreferredWidth()),
Math.min(height, getPreferredHeight()));
}

protected void paint(Graphics graphics) {

graphics.clear();
graphics.setBackgroundColor(0xe8edef);

graphics.drawBitmap(0, 0, getWidth(), getHeight(), _currentPicture, 0,
0);
}

protected boolean navigationClick(int status, int time) {
fieldChangeNotify(0);
return true;
}

public boolean keyChar(char key, int status, int time) {
if (key == Characters.ENTER) {
fieldChangeNotify(0);
return true;
}
return false;
}
}

No comments:

Post a Comment