javahtmlcssgwtuibinder

GWT add widget UIBundle style at runtime


In a GWT application i am declaring the .css styles inside the UiBinder (ui.xml)

For example:

<ui:Style>
    .input {
        background:green;
    }
</ui:Style>

And if i declare a Widget inside the UiBinder i reference the Style i was like below:

<g:Button styleName="{Style.input}"/>

which is fine.

My problem is that i want to apply that style in a Widget that i add at run time. For example a text box:

TextBox box = new TextBox();
box.setStyleName("input");

I have tried all the possible compinatations (e.g. "input", "{Style.input}"), but without any luck. I know that GWT compiles the styles inside a UiBinder file so the Widgets end up with something like "class="GLIX78"".

Is there any way i can achieve adding a style which is declared at UiBinder in a Widget at runtime?

Thanks,


Solution

  • You can reference the style, which you have declared in UiBinder. But you need to take some additional steps. Look at this example:

    UiBinder

      <!-- (1) declare your style , remember to set the type attribute correctly - you should place your package.WidgetName.StyleName in there -->
     <ui:style type='z.client.TEstWidget.MyStyle'>
        .blackBG {
            background-color: black;
        }
    
        .grayBG {
            background-color: gray;
        }
      </ui:style>
    
    
      <g:HTMLPanel>
        <g:Label ui:field="myLabel" styleName="{style.grayBG}">test</g:Label>
        <g:Button ui:field="myButton">change style</g:Button>
      </g:HTMLPanel>
    

    Widget code

    public class TEstWidget extends Composite {
    
        private static TEstUiBinder uiBinder = GWT.create(TEstUiBinder.class);
    
        interface TEstUiBinder extends UiBinder<Widget, TEstWidget> {
        }
    
        // declare the style (2)
        interface MyStyle extends CssResource {
    
            String blackBG();
    
            String grayBG();
        }
    
        // (3) here you make reference to the style declared in uibinder
        @UiField
        MyStyle style;
    
        @UiField
        Button myButton;
    
        @UiField
        Label myLabel;
    
        public TEstWidget() {
            initWidget(uiBinder.createAndBindUi(this));
        }
    
    
        @UiHandler("myButton")
        public void onClick(ClickEvent event) { 
            // change the background of the label
            // (4) this is how you can use your style
            myLabel.removeStyleName( style.grayBG());
            myLabel.addStyleName(style.blackBG());
        }
    }