Как выделить кнопку, когда сфокусируешься на ней в ежевике? - PullRequest
0 голосов
/ 21 июля 2011

Я хочу сделать кнопку Blackberry с изображениями, одно изображение должно отображаться в фокусе, а другое - в несфокусированном.

или даже вы можете сказать синий цвет, когда фокус выключен (по умолчанию), и красный цвет, когда фокус включен, как я могу добиться этого?

см. Мой пользовательский класс

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

     public class MyButtonField extends Field {

     // private int backgroundColour = 0xFFFFFF;
     private Bitmap button;
     private Bitmap on; //= Bitmap.getBitmapResource("img/pink_scribble.bmp");
     private Bitmap off; // = Bitmap.getBitmapResource("img/blue_scribble.bmp");
     private int fieldWidth;
     private int fieldHeight;
    // private int buffer = (Display.getHeight() - 105) / 2;
     private String text;
     private Font fieldFont;
     private boolean btn_text = true;
     private static long style = Field.FIELD_HCENTER | Field.FIELD_VCENTER;

     public MyButtonField(String _text, String onpath, String offpath)  {
      super(Field.FOCUSABLE | style);
      text = _text;
      on = Bitmap.getBitmapResource(onpath);
      off = Bitmap.getBitmapResource(offpath);
      fieldWidth = on.getWidth();
      fieldHeight = on.getHeight();
      button = off;
      fieldFont = FieldFont();
      } 



     public MyButtonField(String _text, String onpath, String offpath, String focusedpath){
             this(_text, onpath, offpath);
     }

     public MyButtonField(String _text, String onpath, String offpath, boolean btn_text) {
     this(_text, onpath , offpath);
     this.btn_text = btn_text;
     }

     public MyButtonField(String _text, String onpath, String offpath, boolean btn_text,     int style, int size)
     {
        this(_text, onpath , offpath, btn_text);
        fieldFont = FieldFont(style, size);
     }
     public MyButtonField(String _text, String onpath, String offpath, long style)
     {
     this(_text, onpath , offpath);
   }
    // public MyButtonField(String _text, String onpath, String offpath, int background)
   // {
   //    this(_text, onpath , offpath);
    ////     backgroundColour = background;
    // }
     protected boolean navigationClick(int status, int time) {
    fieldChangeNotify(1);
    return true;
     }

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

     protected void onUnfocus() {
    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 Font FieldFont() 
    {
    try {
    FontFamily theFam = FontFamily.forName("SYSTEM");
    return theFam.getFont(net.rim.device.api.ui.Font.PLAIN, 14);
    } catch (ClassNotFoundException ex) {
    ex.printStackTrace();
    }
    return null;
    }

    public static Font FieldFont(int style, int size) 
    {
    try {
    FontFamily theFam = FontFamily.forName("SYSTEM");
    return theFam.getFont(style, size);
    } catch (ClassNotFoundException ex) {
    ex.printStackTrace();
    }
    return null;
    }

    protected void drawFocus(Graphics graphics, boolean on) {
        if (on) {
            //graphics.setColor(Color.RED);

           int width = getWidth();
           int height = getHeight();
           graphics.drawBitmap(0, 0, fieldWidth, fieldHeight, button, 0, 0);

           //Draw a border around the field.
          /*
           graphics.fillRoundRect(0, 0, 3, height,10,10); //Left border
           graphics.fillRoundRect(0, 0, width, 3,10,10); //Top border
           graphics.fillRoundRect(width-3, 0, 3, height,10,10); //Right border
           graphics.fillRoundRect(0, height-3, width, 3,10,10); //Bottom border
         */
           graphics.setColor(Color.GRAY);
        }
        invalidate();
    }

     public void setFocusImage()
     {
     button = on;
     }
     public void setUnFocusImage()
    {
     button = off;
     }

     protected void fieldChangeNotify(int context) {
     this.getChangeListener().fieldChanged(this, context);
     }

    protected void paint(Graphics graphics) 
      {
     graphics.drawBitmap(0, 0, fieldWidth, fieldHeight, button, 0, 0);
     graphics.setFont(getFont().derive(Font.PLAIN, 8));
     graphics.setColor(Color.LIGHTGRAY);
    // graphics.fillRoundRect(0, 0, fieldWidth, fieldHeight, 8, 8);
    //  graphics.setColor(Color.GRAY);
        //graphics.drawRoundRect(0, 0, fieldWidth, fieldHeight, 8, 8);

     if(btn_text)
         graphics.drawText(text, 10, 5);
    }

       public String getLabel() {
        return text;
        }
        }

Ответы [ 3 ]

1 голос
/ 21 июля 2011

Вы должны переопределить onFocus(), onUnfocus() и paint().

См. Поле пользовательских кнопок Статья.

0 голосов
/ 22 июля 2011

Почему вы переопределяете метод drawFocus ().Поскольку вы переопределяете метод рисования и onFocus & onUnFocus для изменения растрового изображения, вам не нужно ничего делать в drawFocus ().Используйте метод рисования, чтобы нарисовать что-нибудь.Каждый раз, когда вы вызываете Invalide (), он будет запрашивать перерисовку экрана / поля.Поэтому удалите весь код из drawFocus и добавьте его в метод рисования.

protected void drawFocus(Graphics graphics, boolean on) 
{
    // Do nothing
}

protected void paint(Graphics graphics) 
{
        graphics.drawBitmap(0, 0, fieldWidth, fieldHeight, button, 0, 0);
        graphics.setFont(getFont().derive(Font.PLAIN, 8));
        graphics.setColor(Color.LIGHTGRAY);

        if(btn_text)
            graphics.drawText(text, 10, 5);
}

Надеюсь, это решит вашу проблему.

0 голосов
/ 22 июля 2011

Возможно, вам не хватает этого пункта:

public boolean isFocusable() {
    return true;
}

Это должно быть в вашем пользовательском Field, чтобы среда пользовательского интерфейса BB могла понять, что это поле для фокусировки.Да, это странно, так как вы уже передаете Field.FOCUSABLE в конструктор, однако просто попробуйте.

...