问题
How can I get add an icon with text to a menu item in GWT? The following does not work:
<ui:with field='res' type='my.package.MyResources' />
<g:MenuItem text="test"><g:Image resource="{res.myIcon}" /></g:MenuItem>
Resulting error:
Not allowed in an HTML context: <g:Image resource='{res.myIcon}'>
public interface MyResources extends ClientBundle {
@Source("myIcon.png")
ImageResource myIcon();
}
回答1:
The MenuItem allows only HTML or plain text as its content. So you cannot use an Image widget, but you can very well use an <img> element and retrieve the image URL from the ImageResource referenced by <ui:with> using getSafeUri() (you can call no-arg methods in UiBinder templates). In your case:
<g:MenuItem>
<img src="{res.myIcon.getSafeUri}"/><span>Your text here</span>
</g:MenuItem>
Or programmatically, using a simple template:
public interface MyTemplate extends SafeHtmlTemplates {
@Template("<img src=\"{0}\" /><span>{1}</span>")
SafeHtml createItem(SafeUri uri, SafeHtml message);
}
instantiated via:
MyTemplate template = GWT.create(MyTemplate.class)
and used like so:
new MenuItem(template.createItem(
yourResources.myIcon().getSafeUri(),
SafeHtmlUtils.fromString("Your text here")));
回答2:
Please try this
<g:MenuItem>
<div class="className"/> MyMenuWithImg
</g:MenuItem>
That css class have the background image.
回答3:
I ended up extending the GWT MenuItem class in a way that one can supply an ImageResource from ui-binder:
class MyMenuItem extends MenuItem {
@Uresstructor
public resMenuItem(String text, ImageResource res) {
super(SafeHtmlUtils.fromString(text));
ImageResourceRenderer renderer = new ImageResourceRenderer();
setHTML(renderer.render(res) + " " + text);
}
}
Usage:
<ui:with field='res' type='path.to.MyIconResources' />
<g:MenuBar>
<my:MyMenuItem text="test" icon="{res.myIcon}" />
</g:MenuBar>
If anyone comes up with a better idea (now or in the future) please comment accordingly.
来源:https://stackoverflow.com/questions/16399241/how-to-add-an-icon-to-a-menuitem-in-gwt