GWT 在运行时添加小部件 UIBundle 样式

问题描述 投票:0回答:1

在 GWT 应用程序中,我在 UiBinder (ui.xml) 中声明 .css 样式

例如:

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

如果我在 UiBinder 中声明一个 Widget,我会引用样式,如下所示:

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

这很好。

我的问题是我想在运行时添加的小部件中应用该样式。例如文本框:

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

我已经尝试了所有可能的组合(例如“input”,“{Style.input}”),但没有任何运气。我知道 GWT 编译 UiBinder 文件内的样式,因此小部件最终会出现类似“class =“GLIX78””的内容。

有什么方法可以实现在运行时在 Widget 中添加在 UiBinder 中声明的样式吗?

谢谢,

java html css gwt uibinder
1个回答
3
投票

您可以引用您在 UiBinder 中声明的样式。但您需要采取一些额外的步骤。看这个例子:

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>

小部件代码

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());
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.