它可能会帮助您了解使用<ui:style> 相对于常量静态类名的优势。
使用 <ui:style> 元素,您可以在需要的地方为您的 UI 定义 CSS。
示例:
<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'>
<ui:style>
.pretty { background-color: Skyblue; }
</ui:style>
<div class='{style.pretty}'>
Hello, <span ui:field='nameSpan'/>.
</div>
</ui:UiBinder>
优势
注意:大多数现实世界的项目可能会将其 CSS 保存在单独的文件中。在下面给出的示例中,src 值是相对于 ui.xml 文件的位置的。
样本
<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'>
<ui:style src="MyUi.css" />
<ui:style field='otherStyle' src="MyUiOtherStyle.css">
<div class='{style.pretty}'>
Hello, <span class='{otherStyle.pretty}' ui:field='nameSpan'/>.
</div>
</ui:UiBinder>
首选<span class='{otherStyle.pretty}' 而不是<span class='pretty'。
=======================
编辑
根据@Thomas 在 cmets 的建议,更喜欢使用 <ui:with>
有时您的模板需要使用来自模板外部的样式或其他对象。使用<ui:with> 元素使它们可用。
<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'
xmlns:g='urn:import:com.google.gwt.user.client.ui'>
<ui:with field='res' type='com.my.app.widgets.logoname.Resources'/>
<g:HTMLPanel>
<g:Image resource='{res.logo}'/>
<div class='{res.style.mainBlock}'>
<div class='{res.style.userPictureSprite}'/>
<div>
Well hello there
<span class='{res.style.nameSpan}' ui:field='nameSpan'/>
</div>
</div>
</g:HTMLPanel>
</ui:UiBinder>
/**
* Resources used by the entire application.
*/
public interface Resources extends ClientBundle {
@Source("Style.css")
Style style();
@Source("Logo.jpg")
ImageResource logo();
public interface Style extends CssResource {
String mainBlock();
String nameSpan();
Sprite userPictureSprite();
}
}
// Within the owner class for the UiBinder template
@UiField Resources res;
...
res.style().ensureInjected();
请参阅Using an external resource 上的 GWT 文档