Wednesday, February 15, 2012

Custom ImageButtonField in Blackberry

Some time we need to create our custom Button using image. Here is example of that custom Blackberry ButtonField so you need to pass two image one for focusable image and another is normal image. When focus got then _on(Focusabe) image will display and when focus lost when _off(UnFocusable) image will be display let's try following code.
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;

public class CustomeImageButton extends Field {

 private Bitmap button;
 private Bitmap on, off;
 private int fieldWidth;
 private int fieldHeight;
 private int buffer = 1;
 private static boolean focus;

 public CustomeImageButton(String _on, String _off) {
  super(Field.FOCUSABLE);
  on = Bitmap.getBitmapResource(_on);
  off = Bitmap.getBitmapResource(_off);
  button = off;
  fieldWidth = button.getWidth() + 2; 
  fieldHeight = button.getHeight() + 5;
 }
 public CustomeImageButton(String _text, Bitmap _on, Bitmap _off) {
  super(Field.FOCUSABLE);
  on = _on;
  off = _off;
  button = off;
  fieldWidth = button.getWidth() + 2; 
  fieldHeight = button.getHeight() + 5;
 }
 protected boolean navigationClick(int status, int time) {
  fieldChangeNotify(1);
  return true;
 }

 protected void onFocus(int direction) {
  focus = true;
  button = on;
  invalidate();
 }

 protected void onUnfocus() {
  focus = false;
  button = off;
  invalidate();
 }

 public int getPreferredWidth() {
  return fieldWidth;
 }

 public int getPreferredHeight() {
  return fieldHeight;
 }

 protected void layout(int arg0, int arg1) {
  setExtent(getPreferredWidth(), getPreferredHeight());
 }

 public static boolean isFocused() {
  return focus;
 }

  protected void drawFocus(Graphics graphics, boolean on) {
         
  } 
 protected void paint(Graphics graphics) {
  graphics.drawBitmap(buffer, 4, fieldWidth, fieldHeight, button, 0, 0);
 }

 public boolean isFocus() {
  return focus;
 }
}

Now add this button on MainScreen
      add(new CustomeImageButton("img/play_on.png", "img/play_off.png"));
      add(new CustomeImageButton("img/play_on.png", "img/play_off.png"));


Now here following screen display two button. Both are same but one button focus got and another is focus lost.

2 comments:

  1. thnx , you saved me from a big headache

    ReplyDelete
  2. nice example, i wonder if u have more with layout and listeners for button

    ReplyDelete