views:

934

answers:

1

Hi, I have a class that extends from ButtonField :

class BitmapButtonField extends ButtonField
{
    private Bitmap _bitmap;
    private int _buttonWidth;
    private int _buttonHeight;

    BitmapButtonField(Bitmap bitmap, int buttonWidth, int buttonHeight, long style) 
    {    
        super(style);
        _buttonWidth = buttonWidth;
        _buttonHeight = buttonHeight;
        _bitmap = bitmap;
    }

    public int getPreferredHeight() 
    {
        return _buttonHeight;
    }

    public int getPreferredWidth() 
    {
        return _buttonWidth;
    }

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

    protected void paint(Graphics graphics) 
    {       
        // THIS IS NOT CENTERED
        int x = (getPreferredWidth() - _bitmap.getWidth()) >> 1;
        graphics.drawBitmap(x, 0, _bitmap.getWidth(), _bitmap.getHeight(), _bitmap, 0, 0);

        // THIS IS NOT LEFTMOST, TOPMOST
        graphics.drawBitmap(0, 0, _bitmap.getWidth(), _bitmap.getHeight(), _bitmap, 0, 0);
    }
}

If you could see from my comments on the paint method, clearly the ButtonField 0,0 position is not exactly in leftmost and topmost corner of the button, somehow it is padded with unknown offset, so this makes centering the image is difficult.

But if I extend from a Field class, the problem goes away, but I need to keep extending from ButtonField since I need the ButtonField border and focus style (blue-white rounded rectangle), I just need to display centered image on a ButtonField, and still retaining all of the standard ButtonField attributes.

Is there a way to eliminate the padded offset in paint method on a ButtonField? I've tried setPadding and setMargin but no such luck. Thanks a lot!

A: 

In paint() to define x offset for image there is a code:

int x = (getPreferredWidth() - _bitmap.getWidth()) >> 1;

It is ok, still button can have other size, because of:

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

Try to use

protected void layout(int width, int height) 
{
    setExtent(getPreferredWidth(), getPreferredHeight());
}
Max Gontar