gwtuibinderclientbundle

GWT ImageResource background-position


I'm attempting to use a single .png as a button with a hover effect (a la this) in GWT using UIBinder but am having a tough time.

Here's my ui.xml file:

<ui:with field="functionResources" type="myapp.client.application.functions.FunctionResources"/>

<ui:style>

    .clickableIcon{
        cursor: hand;
        cursor: pointer;            
    }

    .clickableIcon:hover{
        cursor: hand;
        cursor: pointer;                        
        background-position: 0 -76px;
        border: 1px solid blue;
    }
</ui:style>

<g:VerticalPanel ui:field="buttonPanel">
    <g:Image ui:field="survivalIcon" debugId="survivalIcon" width="76px" resource="{functionResources.survivalIcon}" styleName="{style.clickableIcon}"/>

</g:VerticalPanel> 

I'm able to get the .png bundled and displayed in the browser just fine. However, my :hover CSS isn't working as desired. It will, indeed, display a blue border around the image when I hover, so I know the CSS is working, but the image doesn't change.

It looks like the bundled image is overriding the background-position property as 0 0 in the element style itself, which negates my class-level styling. Is there any way to tell GWT not to set the background-position for a bundled ImageResource? Or is there a better way to do this altogether?

Thanks.


Solution

  • From the poor documentation I've found on the web, you cannot override g:Image's background-position property.

    An alternative would be to use GWT's sprite system to generate a background-image, on which you will be able to override the background-position property.

    For example,

    <div class="{functionResources.style.survivalIcon} {style.clickableIcon}"/>
    

    where FunctionResources would have:

    public interface FunctionResources extends ClientBundle {
        public interface Style extends CssResource {
            String survivalIcon();
        }
    
        Style style();
        ImageResource survivalIconImage();
    }
    

    and, in a separate CSS file named style.css, you'd have:

    @sprite .survivalIcon {
        gwt-image: "survivalIconImage";
    }
    

    This will generate a div, with the background-image you wanted. You will be able to modify the div's background-position property at will.

    Of course, this method can be applied to any DOM element that supports background-image.